MVC 6 404 Not Found

前端 未结 6 1486
我在风中等你
我在风中等你 2020-12-06 12:04

Instead of getting a HTTP 404 response, I\'d like to have a generic 404 Not Found page (HTTP 200). I know you can set that up in MVC 5 with



        
6条回答
  •  情歌与酒
    2020-12-06 12:19

    If you have a standard ASP.NET 5 Web application template project you can get a really nice solution that will handle both keeping the error status code at the same time as you serve the cshtml file of your choice.

    Startup.cs, in the Configure method

    Replace

    app.UseExceptionHandler("/Error");
    

    with

    app.UseStatusCodePagesWithReExecute("/Home/Errors/{0}");
    

    Then remove the following catchall:

    app.Run(async (context) => 
    { 
       var logger = loggerFactory.CreateLogger("Catchall Endpoint"); 
       logger.LogInformation("No endpoint found for request {path}", context.Request.Path); 
       await context.Response.WriteAsync("No endpoint found - try /api/todo."); 
    });
    

    In HomeController.cs

    Replace the current Error method with the following one:

    public IActionResult Errors(string id) 
    { 
      if (id == "500" | id == "404") 
      { 
        return View($"~/Views/Home/Error/{id}.cshtml"); 
      }
    
      return View("~/Views/Shared/Error.cshtml"); 
    }
    

    That way you can add error files you feel the users can benefit from (while search engines and such still get the right status codes)

    Now add a folder named Error in ~Views/Home folder Create two .cshtml files. Name the first one 404.cshtml and the second one 500.cshtml.

    Give them some useful content and the start the application and write something like http://localhost:44306/idonthaveanendpointhere and confirm the setup works.

    Also press F12 developer tools and confirm the status code is 404.

提交回复
热议问题