Net Core中使用ExceptionFilter过滤器的方法
这篇文章主要介绍了.Net Core中使用ExceptionFilter过滤器的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
Net Core中有各种Filter,分别是AuthorizationFilter、ResourceFilter、ExceptionFilter、ActionFilter、ResultFilter。可以把他们看作是.Net Core自带的AOP的扩展封装。
今天来看其中的一种:ExceptionFilter(用于全局的异常处理)
首先新建一个.Net Core MVC的项目
新建一个控制器:
这里我们可以看到代码运行到16行时会报一个索引项超出集合范围的错误
按照常规的思维我们在代码中会加异常处理,如下:
1 2 3 4 5 6 7 8 9 10 11 | try { var range = Enumerable.Range(1, 3).ToArray(); var result = range[4]; return View(); } catch (Exception ex) { throw new Exception(ex.Message); } |
但是每个方法都这样加会不会觉得很烦?有没有想过只写一次就可以了
上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ViewFeatures; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ExceptionFilter.Filter { public class CustomerExceptionFilter : Attribute, IExceptionFilter { private readonly IHostingEnvironment _hostingEnvironment; private readonly IModelMetadataProvider _modelMetadataProvider; public CustomerExceptionFilter(IHostingEnvironment hostingEnvironment, IModelMetadataProvider modelMetadataProvider) { _hostingEnvironment = hostingEnvironment; _modelMetadataProvider = modelMetadataProvider; } /// <summary> /// 发生异常进入 /// </summary> /// <param name="context"></param> public async void OnException(ExceptionContext context) { if (!context.ExceptionHandled) //如果异常没有处理 { if (_hostingEnvironment.IsDevelopment()) //如果是开发环境 { var result = new ViewResult { ViewName = "../Handle/Index" }; result.ViewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState); result.ViewData.Add( "Exception" , context.Exception); //传递数据 context.Result = result; } else { context.Result = new JsonResult( new { Result = false , Code = 500, Message = context.Exception.Message }); } context.ExceptionHandled = true ; //异常已处理 } } } } |
我们在方法中先以特性来使用,加上这句代码:
1 | [TypeFilter( typeof (CustomerExceptionFilter))] |
之后会跳到这个视图:../Handle/Index ,会将异常信息传入到此视图
视图页代码:
1 | < p >Message:@ViewData["Exception"]</ p > |
(可以自行封装。。。)
我们还可以定义成全局的
在Startup类中的ConfigureServices方法中加入这句代码
1 2 3 4 5 | services.AddControllersWithViews(option => { option.Filters.Add<CustomerExceptionFilter>(); }); //3.0以下的版本好像应该这样写:services.AddMvc(); |
到此这篇关于.Net Core中使用ExceptionFilter过滤器的方法的文章就介绍到这了