asp.net MVC3上的自定义错误页面

Joh*_*ros 144 error-handling asp.net-mvc-3

我正在开发一个MVC3基础网站,我正在寻找一个处理错误的解决方案,并为每种错误渲染自定义视图.因此,假设我有一个"错误"控制器,其主要操作是"索引"(通用错误页面),并且此控制器将针对用户可能出现的错误(如"Handle500"或"HandleActionNotFound")执行更多操作.

因此,网站上可能发生的每个错误都可能由此"错误"控制器处理(例如:"Controller"或"Action"未找到,500,404,dbException等).

我使用Sitemap文件来定义网站路径(而不是路由).

这个问题已经回答了,这是对Gweebz的回复

我的最终applicaiton_error方法如下:

protected void Application_Error() {
//while my project is running in debug mode
if (HttpContext.Current.IsDebuggingEnabled && WebConfigurationManager.AppSettings["EnableCustomErrorPage"].Equals("false"))
{
    Log.Logger.Error("unhandled exception: ", Server.GetLastError());
}
else
{
    try
    {
        var exception = Server.GetLastError();

        Log.Logger.Error("unhandled exception: ", exception);

        Response.Clear();
        Server.ClearError();
        var routeData = new RouteData();
        routeData.Values["controller"] = "Errors";
        routeData.Values["action"] = "General";
        routeData.Values["exception"] = exception;

        IController errorsController = new ErrorsController();
        var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
        errorsController.Execute(rc);
    }
    catch (Exception e)
    {
        //if Error controller failed for same reason, we will display static HTML error page
        Log.Logger.Fatal("failed to display error page, fallback to HTML error: ", e);
        Response.TransmitFile("~/error.html");
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 201

这是我如何处理自定义错误的示例.我定义了一个ErrorsController处理不同HTTP错误的动作:

public class ErrorsController : Controller
{
    public ActionResult General(Exception exception)
    {
        return Content("General failure", "text/plain");
    }

    public ActionResult Http404()
    {
        return Content("Not found", "text/plain");
    }

    public ActionResult Http403()
    {
        return Content("Forbidden", "text/plain");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我订阅了Application_Errorin Global.asax并调用了这个控制器:

protected void Application_Error()
{
    var exception = Server.GetLastError();
    var httpException = exception as HttpException;
    Response.Clear();
    Server.ClearError();
    var routeData = new RouteData();
    routeData.Values["controller"] = "Errors";
    routeData.Values["action"] = "General";
    routeData.Values["exception"] = exception;
    Response.StatusCode = 500;
    if (httpException != null)
    {
        Response.StatusCode = httpException.GetHttpCode();
        switch (Response.StatusCode)
        {
            case 403:
                routeData.Values["action"] = "Http403";
                break;
            case 404:
                routeData.Values["action"] = "Http404";
                break;
        }
    }

    IController errorsController = new ErrorsController();
    var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
    errorsController.Execute(rc);
}
Run Code Online (Sandbox Code Playgroud)

  • 只是一点点说明.由于我想在每个ActionResult上渲染一个View(404,500等),我返回了一个View.但是,我尝试了解Application_Error内容,并且在失败的情况下返回静态HTML页面.(如果有人愿意,我可以发布代码) (4认同)
  • 我无法在MVC3上使用此解决方案来获取razor视图.返回视图(模型)仅作为示例获取空白屏幕. (4认同)
  • 添加了TrySkipIisCustomErrors来修复集成的IIS7.请参阅http://stackoverflow.com/questions/1706934/asp-net-mvc-app-custom-error-pages-not-displaying-in-shared-hosting-environment (2认同)
  • 通过显式指定响应的内容类型来修复:`Response.ContentType ="text/html";` (2认同)

Sha*_*man 18

这里有更多文章如何使用MVC创建自定义错误页面http://kitsula.com/Article/MVC-Custom-Error-Pages.


Bre*_*red 6

您也可以在Web.Config文件中执行此操作.这是一个适用于IIS 7.5的示例.

     <system.webServer>
          <httpErrors errorMode="DetailedLocalOnly" defaultResponseMode="File">
                <remove statusCode="502" subStatusCode="-1" />
                <remove statusCode="501" subStatusCode="-1" />
                <remove statusCode="412" subStatusCode="-1" />
                <remove statusCode="406" subStatusCode="-1" />
                <remove statusCode="405" subStatusCode="-1" />
                <remove statusCode="404" subStatusCode="-1" />
                <remove statusCode="403" subStatusCode="-1" />
                <remove statusCode="401" subStatusCode="-1" />
                <remove statusCode="500" subStatusCode="-1" />
                <error statusCode="500" path="/notfound.html" responseMode="ExecuteURL" />
                <error statusCode="401" prefixLanguageFilePath="" path="/500.html" responseMode="ExecuteURL" />
                <error statusCode="403" prefixLanguageFilePath="" path="/403.html" responseMode="ExecuteURL" />
                <error statusCode="404" prefixLanguageFilePath="" path="/404.html" responseMode="ExecuteURL" />
                <error statusCode="405" prefixLanguageFilePath="" path="/405.html" responseMode="ExecuteURL" />
                <error statusCode="406" prefixLanguageFilePath="" path="/406.html" responseMode="ExecuteURL" />
                <error statusCode="412" prefixLanguageFilePath="" path="/412.html" responseMode="ExecuteURL" />
                <error statusCode="501" prefixLanguageFilePath="" path="/501.html" responseMode="ExecuteURL" />
                <error statusCode="502" prefixLanguageFilePath="" path="/genericerror.html" responseMode="ExecuteURL" />
           </httpErrors>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)