且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何创建ASP.NET MVC 3自定义404错误页面?

更新时间:2023-01-10 10:21:25

您应该配置

<httpErrors>

<system.webServer> 

节组在你的web.config文件。

section group in your web.config file.

请参考这篇文章:

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

此外,你可以使用你在你的问题联系在一起的差错控制,但是最初的流动应该由IIS进行管理。通过这一部分,您可以指示IIS,它应该执行这是由你的控制器管理的网址。

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.

也请照顾一下贵控制器的行动是提出的解决方案返回200 OK,这可能会产生混淆的浏览器正确Response.Status属性字符串。例如:

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

}

配置例如:

<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>

您可以使用子状态code属性控制404.3等。

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