How to create custom 404 Error pages in ASP.NET MV

2019-04-08 14:15发布

问题:

what is the best way to create custom error pages in ASP.NET MVC 3? The one I am particularly interested in is a 404 error, but also 403, and others. I am new to the MVC framework, traditionally I come from a PHP background, but am learning quickly.

I did my research before posting this question and came across this link: Custom error pages on asp.net MVC3

That solution seems simple although when I try to implement that on my machine, I get a problem with the following line: IController errorsController = new ErrorsController(); inside the Application_Error() function. It says "The type or namespace name 'ErrorsController' could not be found (are you missing a using directive or an assembly reference?".

Thank you in advance for help you may provide.

回答1:

You should configure

<httpErrors>

section under

<system.webServer> 

section group in your web.config file.

Please refer to this article:

http://www.iis.net/ConfigReference/system.webServer/httpErrors

Additionally you can use the error controller which you linked in your question, however initial flow should be managed by IIS. By this section you can instruct IIS that it should execute urls which are managed by your controller.

Also please take care about proper Response.Status property string in your controller's actions as proposed solution returns "200 OK" which may be confusing for browsers. For example

public class ErrorsController : Controller
{
    public ActionResult NotFound()
    {
        Response.Status = "404 Not Found";
        return View();
    }

    public ActionResult ServerError()
    {
        byte[] delay = new byte[1];
        RandomNumberGenerator prng = new RNGCryptoServiceProvider();

        prng.GetBytes(delay);
        Thread.Sleep((int)delay[0]);

        IDisposable disposable = prng as IDisposable;
        if (disposable != null) { disposable.Dispose(); }
        Response.Status = "500 Internal Server Error";
        return View();
    }

}

Configuration example:

<httpErrors defaultPath="/error.htm" errorMode="Custom" existingResponse="Replace" defaultResponseMode="ExecuteURL">
      <remove statusCode="500" subStatusCode="-1" />
      <remove statusCode="404" subStatusCode="-1" />
      <error statusCode="500" path="/errors/servererror/" responseMode="ExecuteURL" />
      <error statusCode="404" path="/errors/notfound/" responseMode="ExecuteURL" />
  </httpErrors>

You can control 404.3 and other using "subStatusCode" attribute.



回答2:

Add an Application_EndRequest method to your MvcApplication to call a view for your "not found" page, per Marco's Better-Than-Unicorns MVC 404 Answer.