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>


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值