Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What pattern is being done in the Global.asax.cs file in ASP.NET MVC 4?

I have never come across this pattern of code right here. Would anyone care to explain it to me? (Or is there even a pattern here? Is there a reason why this was done like this? What benefits is this giving?) I'm new at general programming, and this is a very interesting one to me:

Global.asax.cs

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        //...
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        //...
    }

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

RouteConfig.cs

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

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}
like image 420
JCCV Avatar asked Sep 14 '12 00:09

JCCV


1 Answers

You could easily write the code in your sample like this:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    GlobalConfiguration.Configuration.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional });

    RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    RouteTable.Routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { 
            controller = "Home", 
            action = "Index", 
            id = UrlParameter.Optional });
}

However, as the amount of necessary configuration grows, it makes sense to split it up into several logically related chunks. ASP.NET MVC supports this fairly well, and the default project template is just trying to guide you towards doing so.

like image 78
millimoose Avatar answered Sep 20 '22 00:09

millimoose