了解 Global.asax.cs 中的 Application_Start

Rod*_*Rod -1 .net c# asp.net asp.net-mvc

我正在使用.NETFramework v4.7.2并且我想管理我Global.asax.cs以更改我网站的行为。但是我很难理解每一行:

public class MvcApplication : HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();                         // (1)

        GlobalFilters.Filters.Add(new HandleErrorAttribute());       // (2)

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

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

        GlobalConfiguration.Configuration.Routes.MapHttpRoute(       // (5)
            name: "DefaultApi",
            routeTemplate: "api/{controller}"
        );
    }
}
Run Code Online (Sandbox Code Playgroud)
  • (1) 有人对它的作用有一个简短的解释吗?
  • (2) 它可以MvcApplication显示错误页面(如 404、500、...)
  • (3) 它忽略所有带有.axd扩展名的路径?
  • (4) 它创建一个默认页面并调用HomeController.cs.cshtml显示一些东西?如何更改为只显示一个简单的index.html
  • (5) 它创建api和调用nameController.cs来接收GET和/或POST请求?
    • 如何配置简单/api/Login请求的接收POST?这不起作用并且只给出404 (Not Found)415 (Unsupported Media Type)错误:

. 登录控制器.cs :

[HttpPost]
[ActionName("Login")]
[Route("api/[controller]")]
public HttpResponseMessage LoginPost([FromBody] LoginJson json)
{
    return Request.CreateResponse(HttpStatusCode.OK);
}
Run Code Online (Sandbox Code Playgroud)

登录Json.cs:

public class LoginJson
{
    public string Username { get; set; }
    public string Password { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

jQuery:

$.ajax({
        url: '/api/Login',
        type: 'POST',
        dataType: "json",
        contentType: "application/json, charset=utf-8",
        data: JSON.stringify({
            Username: username,
            Password: password
        }),
        ...
});
Run Code Online (Sandbox Code Playgroud)

Iva*_*čić 5

1)我认为这将解释所有关于领域:https : //exceptionnotfound.net/asp-net-mvc-demystified-areas/

2) 是的,但它允许您自定义发生错误/异常时默认情况下发生的情况。例如,您可以设置是否出现问题重定向到其他控制器...

3) 在评论中回答:What is routes.IgnoreRoute("{resource}.axd/{*pathInfo}") -将 IgnoreRoute 放入 MVC 的路由配置的原因是为了确保 MVC 不会尝试处理要求。这是因为 .axd 端点需要由另一个 HTTP 处理程序(不属于 MVC 的处理程序)处理才能为脚本提供服务。

4)不,它只是设置到达控制器内部动作的默认方式......动作告诉返回什么(html或cshtml或..)......返回常规html,例如:

public ActionResult Index()
{
    return Content("<html></html>");
}
Run Code Online (Sandbox Code Playgroud)

5) 与 4) 类似,这是 Web API 请求的默认路由。您的 API 调用是正确的,但您收到的错误意味着您发送到该 API 的请求是错误的,请参阅此问题:不支持的媒体类型 ASP.NET Core Web API