29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Creating and Registering a Simple Route<br />

Once you have a URL pattern in mind, you can use it to define a route. Routes are defined in the RouteConfig.cs file,<br />

which is in the App_Start project folder. You can see the initial content that Visual Studio defines for this file in Listing 15-5.<br />

Listing 15-5. The Default Contents of the RouteConfig.cs File<br />

using System;<br />

using System.Collections.Generic;<br />

using System.Linq;<br />

using System.Web;<br />

using System.Web.Mvc;<br />

using System.Web.Routing;<br />

namespace UrlsAndRoutes {<br />

public class RouteConfig {<br />

public static void RegisterRoutes(RouteCollection routes) {<br />

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");<br />

}<br />

}<br />

}<br />

routes.MapRoute(<br />

name: "Default",<br />

url: "{controller}/{action}/{id}",<br />

defaults: new { controller = "Home", action = "Index",<br />

id = UrlParameter.Optional }<br />

);<br />

The static RegisterRoutes method that is defined in the RouteConfig.cs file is called from the<br />

Global.asax.cs file, which sets up some of the core MVC features when the application is started. You can see the<br />

default contents of the Global.asax.cs file in Listing 15-6, and I have highlighted the call to the<br />

RouteConfig.RegisterRoutes method, which is made from the Application_Start method.<br />

Listing 15-6. The Default Contents of the Global.asax.cs File<br />

using System;<br />

using System.Collections.Generic;<br />

using System.Linq;<br />

using System.Web;<br />

using System.Web.Mvc;<br />

using System.Web.Routing;<br />

namespace UrlsAndRoutes {<br />

}<br />

public class MvcApplication : System.Web.HttpApplication {<br />

protected void Application_Start() {<br />

AreaRegistration.RegisterAllAreas();<br />

RouteConfig.RegisterRoutes(RouteTable.Routes);<br />

}<br />

}<br />

The Application_Start method is called by the underlying ASP.NET platform when the MVC application is first<br />

365

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!