nawaz uddin
nawaz uddin

Reputation: 365

Custom Route to remove controller name from Areas

I want to remove the controller name from the URL in Areas

http://example.com/AreasName/my-page

I try this

 context.MapRoute("AreasName_default", "AreasName/{action}/{id}", new {action = "Index", id = UrlParameter.Optional });

But it's getting an error:

"The matched route does not include a 'controller' route value, which is required".

Upvotes: 0

Views: 283

Answers (1)

Victor
Victor

Reputation: 8950

Try to use attribute routing for area instead of calling the MapRoute():

[RouteArea("AreasName")]   
[Route("{action}/{id}")]

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    // url: /AreasName/about/id
    public ActionResult About(string id)
    {
        ViewBag.Message = "Message...";

        return View();
    }
    ...
}

To enabling attribute routing it is necassary to add a call to routes.MapMvcAttributeRoutes() method with in RegisterRoutes() method of RouteConfig.cs file:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    // Enabling attribute routing. Recommend to put attribute routes in the route table before traditional routes.
    routes.MapMvcAttributeRoutes();

    // Additional calls
    routes.MapRoute(...)
}

Upvotes: 1

Related Questions