Attribute Routing in MVC 5
Prior to MVC 5, you could map URLs to specific actions and controllers by calling routes.MapRoute(...) in the RouteConfig.cs file. This is where the URL of the homepage ( Home/Index ) is stored. However, if you change the default route as shown below,
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
remember that this will affect the URLs of other actions and controllers. For example, if you had a controller class named ExampleController and an action method inside it called DoSomething , then the expected default ExampleController/DoSomething will no longer work because the default route has been changed.
The workaround for this is to not spoil the default route and create new routes in the RouteConfig.cs file for other actions and controllers, for example,
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "Example", url: "hey/now", defaults: new { controller = "Example", action = "DoSomething", id = UrlParameter.Optional } );
Now the DoSomething action of the ExampleController class will be mapped to the hey/now URL. But this can be tedious to do every time you want to define routes for different activities. So in MVC 5, you can now add attributes to match URLs with such actions,
public class HomeController : Controller { // url is now 'index/' instead of 'home/index' [Route("index")] public ActionResult Index() { return View(); } // url is now 'create/new' instead of 'home/create' [Route("create/new")] public ActionResult Create() { return View(); } }
Chris Gong Jun 05 '17 at 14:26 2017-06-05 14:26
source share