ASP.NET MVC3 Custom ErrorPages 500/404

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>


發佈了42 篇原創文章 · 獲贊 191 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章