对于Asp.Net MVC 项目中,对于异常情况下,会跳转到自己定义好的页面,这时就用到了MVC中的异常过滤器(Exception Filters)
(1)一旦action 方法中出现异常,异常过滤器就会控制程序的运行过程,开始内部自动写入运行的代码。MVC为我们提供了编写好的异常过滤器:HandeError。
(2)当action方法中发生异常时,过滤器就会在“~/Views/[current controller]”或“~/Views/Shared”目录下查找到名称为”Error”的View,然后创建该View的ViewResult,并作为响应返回。
一些配置信息
1、在WebConfig中把过滤器配置启动
当自定义异常被捕获时,异常过滤器变为可用。为了能够获得自定义异常,打开Web.config文件,在System.Web.Section下方添加自定义错误信息。
<customErrors mode="On"> </customErrors>
2、创建Error View
在“~/Views/Shared”文件夹下,会发现存在“Error.cshtml”文件,该文件是由MVC 模板提供的,如果没有自动创建,该文件也可以手动完成。
3、绑定异常过滤器
将过滤器绑定到action方法或controller上,不需要手动执行,打开 App_Start folder文件夹中的 FilterConfig.cs文件。在 RegisterGlobalFilters 方法中会看到 HandleError 过滤器已经以全局过滤器绑定成功。
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute());
默认是启动全局过滤器的,也可以删除全局过滤器,那么会将过滤器绑定到action 或controller层,但是不建议这么做,最好是在全局中
[HandleError(ExceptionType = typeof(NullReferenceException), View = "error")] public ActionResult Index() { throw new NullReferenceException(); return View(); }
4、运行过后,在View中显示错误信息
将Error View转换为HandleErrorInfo类的强类型View,并在View中显示错误信息。
@model HandleErrorInfo @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="viewport" content="width=device-width" /> <title>错误</title> </head> <body> <hgroup> <h1>错误。</h1> <h2>处理你的请求时出错。1231321</h2> </hgroup> 错误信息:@Model.Exception.Message<br /> 控制器:@Model.ControllerName <br /> 方法: @Model.ActionName </body> </html>