MVC TIP4:为捕获路由及通用异常处理

本文介绍如何在ASP.NET MVC应用中处理未路由到的URL,通过创建ErrorController来定制不同类型的HTTP错误页面,包括404、500等错误,并在Global.asax中捕获异常进行相应视图的跳转。

对于未路由到的URL,可以如下处理。

1:首先,准备控制器

public  class  ErrorController : Controller
{
     public  ActionResult Index( string  error)
     {
         ViewData[ "Title" ] = "WebSite 网站内部错误" ;
         ViewData[ "Description" ] = error;
         return  View( "Index" );   //全部路由到Error下的Index视图
     }
     public  ActionResult HttpError404( string  error)
     {
         ViewData[ "Title" ] = "HTTP 404- 无法找到文件" ;
         ViewData[ "Description" ] = error;
         return  View( "Index" );
     }
     public  ActionResult HttpError500( string  error)
     {
         ViewData[ "Title" ] = "HTTP 500 - 内部服务器错误" ;
         ViewData[ "Description" ] = error;
         return  View( "Index" );
     }
     public  ActionResult General( string  error)
     {
         ViewData[ "Title" ] = "HTTP 发生错误" ;
         ViewData[ "Description" ] = error;
         return  View( "Index" );
    
}

2:Error下的Index视图

image

代码:

image

3:在Global.aspx中进行处理

添加如下方法:

protected  void  Application_Error( object  sender, EventArgs e)
{
     Response.Clear();
     Exception exception = Server.GetLastError();
     HttpException httpException = exception as  HttpException;
     RouteData routeData = new  RouteData();
     routeData.Values.Add( "controller" , "Error" );
     if  (exception == null )
     {
         routeData.Values.Add( "action" , "Index" );
     }
     else  if  (httpException == null )
     {
         routeData.Values.Add( "action" , "Index" );
     }
     else
     {
         switch  (httpException.GetHttpCode())
         {
             case  404:
                 routeData.Values.Add( "action" , "HttpError404" );
                 break ;
             case  500:
                 routeData.Values.Add( "action" , "HttpError500" );
                 break ;
             default :
                 routeData.Values.Add( "action" , "General" );
                 break ;
         }
     }
     // Pass exception details to the target error View. 
     routeData.Values.Add( "error" , exception.Message);
     // Clear the error on server. 
     Server.ClearError();
     // Call target Controller and pass the routeData. 
     IController errorController = new  ErrorController();
     errorController.Execute( new  RequestContext( new  HttpContextWrapper(Context), routeData));
} 本文转自最课程陆敏技博客园博客,原文链接:http://www.cnblogs.com/luminji/archive/2011/07/31/2122533.html,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值