mvc中的自定义错误页面

时间:2010-01-09 12:04:38

标签: asp.net-mvc

我需要在web.config

上使用customerror显示错误页面

但是watever错误可能是,即使在web.config中我指定了一些版本错误也需要显示错误页面,

我该怎么做?我试过但是网址重定向到

"http://localhost:1966/Error.html?aspxerrorpath=Error.html"

CustomError标记:

<customErrors mode="On" defaultRedirect="Error.html" />

并显示来自mvc的另一个错误页面,而不是地雷。

2 个答案:

答案 0 :(得分:7)

在ASP.NET MVC中,通常使用HandleError属性指定错误处理。默认情况下,它使用名为“错误”的视图来显示自定义错误页面。如果您只想自定义此视图,则可以编辑Views / Shared / Error.aspx。

如果您在特定情况下需要不同的视图,则可以显式提供View属性。

以下是带有自定义错误视图的Controller操作示例:

[HandleError(View = "CustomError")]
public ViewResult Foo() 
{
    // ...
}

有关ASP.NET MVC中的全局错误处理,请参阅this post

答案 1 :(得分:1)

您可以将解决方案用作上面描述的Mark HandleError attrib。

捕获错误的另一个解决方案是拥有所有控制器类派生的基类。并在baseclass ovveride OnException方法中显示一个用户友好的错误视图,例如“〜/ Shared / Error.aspx”

您还需要在根web.config中定义<customErrors mode="On" >才能使此解决方案正常工作。

public class BaseController : Controller
{
        ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public BaseController()
    {
    }

    protected override void OnException(ExceptionContext filterContext)
    {
        // Log the error that occurred.
        log.Fatal("Generic Error occured",filterContext.Exception);

        // Output a nice error page
        if (filterContext.HttpContext.IsCustomErrorEnabled)
        {
            filterContext.ExceptionHandled = true;
            View("Error").ExecuteResult(ControllerContext);
        }
    }

}

上述解决方案可以捕获大部分可能出现的“死亡错误黄屏”。

要处理其他错误,例如404我在global.asax RegisterRoutes(RouteCollection路由)中使用了最后一个mapRoute

// Show a 404 error page for anything else.
            routes.MapRoute(
                "Error",
                "{*url}",
                new { controller = "Shared", action = "Error" }
            );
相关问题