简体   繁体   中英

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 }
        );
    }
}

This isn't a pattern as much an example of the Single Responsibility Principle (SRP) . In Global.asax, we know of the high-level tasks that are required to set things up but we leave the implementation separated.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM