ASP.NET MVC3 Custom ErrorPages 500/404

本文详细介绍了如何在ASP.NET MVC3中自定义错误页面,包括处理404和500错误,通过配置全局过滤器和错误处理类实现个性化的错误展示。

Global.aspx.cs

  1. public static void RegisterGlobalFilters(GlobalFilterCollection filters)  
  2. {  
  3.     filters.Add(new CustomHandlerErrorAttribute());  
  4. }  


CustomHandlerErrorAttribute.cs

  1. public class CustomHandlerErrorAttribute : HandleErrorAttribute  
  2. {  
  3.     public override void OnException(ExceptionContext filterContext)  
  4.     {  
  5.         if (filterContext.ExceptionHandled)  
  6.         {  
  7.             return;  
  8.         }  
  9.   
  10.         filterContext.Controller.ViewData.Model = filterContext.Exception;  
  11.   
  12.         filterContext.Result = new ViewResult   
  13.         {   
  14.             ViewName = "Error",   
  15.             ViewData = filterContext.Controller.ViewData   
  16.         };  
  17.   
  18.         filterContext.ExceptionHandled = true;  
  19.     }  
  20. }  


web.config <system.web>

  1. <customErrors mode="On">  
  2.   <error redirect="/home/error" statusCode="404" />  
  3. </customErrors>  

web.config  <system.webServer>

  1. <httpErrors errorMode="Custom" existingResponse="PassThrough">  
  2. </httpErrors>  

Error.cshtml

  1. <div class="box">  
  2.     @{  
  3.         
  4.         var exception = ViewData.Model;  
  5.         var statusCode = exception == null ? 404 : 500;  
  6.         Response.StatusCode = statusCode;  
  7.         if (statusCode == 404)  
  8.         {  
  9.             <h3>404 Page not found!</h3>  
  10.             <p>没有找到该网页!</p>  
  11.         }  
  12.         else if (statusCode == 500)  
  13.         {  
  14.             <h3>500 程序异常</h3>  
  15.             <p>@exception.Message</p>  
  16.         }  
  17.     }  
  18.     <p style="font-size: 12px; color: Gray">请使用浏览器的后退功能已保证您填写的数据没有丢失!</p>  
  19. </div>  

转载于:https://www.cnblogs.com/mad/archive/2011/10/08/ASP-NET_MVC3_Custom_ErrorPages_500-404.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值