Chapter 11. URL Routing Using Attributes
In Chapter 1, I reviewed the default route that allows new controllers and new actions to be created and automatically routed based on their names alone. This is extremely convenient and works most of the time. However, whether it is for Search Engine Optimization (SEO) purposes or to follow a naming convention and provide a more convenient URL, custom routing allows you to do this.
Prior to MVC 5, routes were defined in the RouteConfig (for MVC) and WebApiConfig (for Web Api) and still can be (as the default route is defined). New in MVC 5 is the ability to route via attributes.
Attribute routing is extremely convenient because it helps unhide the routing and makes it more obvious to the developer how the controller and action can be accessed. Global routing, of course, still serves a useful purpose when you have one or two common routes that apply across multiple controllers and/or actions.
Attribute Routing Basics
Before attribute routing can be used, it must be turned on. This is done in the RouteConfig class inside the App_Start folder. Example 11-1 contains an updated defintion of this class.
Example 11-1. Updated RouteConfig
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.Mvc;usingSystem.Web.Routing;namespaceBootstrapIntroduction{publicclassRouteConfig{publicstaticvoidRegisterRoutes(RouteCollectionroutes){routes.IgnoreRoute("{resource}.axd/{*pathInfo}" ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access