ASP.NET MVC 4中的Global.asax.cs文件中正在执行什么模式?

JCC*_*CCV 7 c# asp.net-mvc design-patterns global-asax asp.net-mvc-4

我从来没有遇到过这种代码模式.有人愿意向我解释一下吗?(或者这里有一个模式吗?有没有理由为什么这样做?这给了什么好处?)我是一般编程新手,这对我来说非常有趣:

的Global.asax.cs

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

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        //...
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        //...
    }
Run Code Online (Sandbox Code Playgroud)

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 }
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

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 }
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

Bab*_*fas 5

这不是单一责任原则(SRP)的一个例子.在Global.asax中,我们知道设置所需的高级任务,但我们将实现分开.


mil*_*ose 5

您可以轻松地在示例中编写代码,如下所示:

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 });
}
Run Code Online (Sandbox Code Playgroud)

但是,随着必要配置量的增加,将其拆分为几个逻辑相关的块是有意义的.ASP.NET MVC支持这一点相当不错,默认项目模板只是试图引导您这样做.

  • @JCCV我不确定我对他们为什么这么做事的权威.我最好的猜测是避免XML配置的问题,例如Javaland中常见的问题.例如,如果要允许将XML配置拆分为多个文件,则需要以配置文件格式显式支持.如果您希望能够包含库中的配置文件,则会变得更加复杂.如果您想在运行时动态生成配置,那就更糟了. (2认同)