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
using
System
;
using
System.Collections.Generic
;
using
System.Linq
;
using
System.Web
;
using
System.Web.Mvc
;
using
System.Web.Routing
;
namespace
BootstrapIntroduction
{
public
class
RouteConfig
{
public
static
void
RegisterRoutes
(
RouteCollection
routes
)
{
routes
.
IgnoreRoute
(
"{resource}.axd/{*pathInfo}" ...
Get ASP.NET MVC 5 with Bootstrap and Knockout.js now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.