ASP.NET MVC3 Custom ErrorPages 500/404

来源:互联网 发布:怎样下载ps软件 编辑:程序博客网 时间:2024/05/17 22:55
Global.aspx.cs

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)        {            filters.Add(new CustomHandlerErrorAttribute());        }

CustomHandlerErrorAttribute.cs

    public class CustomHandlerErrorAttribute : HandleErrorAttribute    {        public override void OnException(ExceptionContext filterContext)        {            if (filterContext.ExceptionHandled)            {                return;            }            filterContext.Controller.ViewData.Model = filterContext.Exception;            filterContext.Result = new ViewResult             {                 ViewName = "Error",                 ViewData = filterContext.Controller.ViewData             };            filterContext.ExceptionHandled = true;        }    }

web.config <system.web>
    <customErrors mode="On">      <error redirect="/home/error" statusCode="404" />    </customErrors>
web.config  <system.webServer>

    <httpErrors errorMode="Custom" existingResponse="PassThrough">    </httpErrors>
Error.cshtml
<div class="box">    @{              var exception = ViewData.Model;        var statusCode = exception == null ? 404 : 500;        Response.StatusCode = statusCode;        if (statusCode == 404)        {            <h3>404 Page not found!</h3>            <p>没有找到该网页!</p>        }        else if (statusCode == 500)        {            <h3>500 程序异常</h3>            <p>@exception.Message</p>        }    }    <p style="font-size: 12px; color: Gray">请使用浏览器的后退功能已保证您填写的数据没有丢失!</p></div>


原创粉丝点击