.Net Core中使用ExceptionFilter过滤器的方法

.Net Core中有各种Filter,分别是AuthorizationFilter、ResourceFilter、ExceptionFilter、ActionFilter、ResultFilter。可以把他们看作是.Net Core自带的AOP的扩展封装。

今天来看其中的一种:ExceptionFilter(用于全局的异常处理)

首先新建一个.Net Core MVC的项目

新建一个控制器:

.Net Core中使用ExceptionFilter过滤器的方法

这里我们可以看到代码运行到16行时会报一个索引项超出集合范围的错误

按照常规的思维我们在代码中会加异常处理,如下:

try { var range = Enumerable.Range(1, 3).ToArray(); var result = range[4]; return View(); } catch (Exception ex) { throw new Exception(ex.Message); }

但是每个方法都这样加会不会觉得很烦?有没有想过只写一次就可以了

上代码:

.Net Core中使用ExceptionFilter过滤器的方法

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></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;//异常已处理 } } } }

我们在方法中先以特性来使用,加上这句代码:

[TypeFilter(typeof(CustomerExceptionFilter))]

.Net Core中使用ExceptionFilter过滤器的方法

之后会跳到这个视图:../Handle/Index ,会将异常信息传入到此视图

视图页代码:

<p>Message:@ViewData["Exception"]</p>

(可以自行封装。。。)

我们还可以定义成全局的

在Startup类中的ConfigureServices方法中加入这句代码

services.AddControllersWithViews(option => { option.Filters.Add<CustomerExceptionFilter>(); }); //3.0以下的版本好像应该这样写:services.AddMvc();

到此这篇关于.Net Core中使用ExceptionFilter过滤器的方法的文章就介绍到这了,更多相关.Net Core使用ExceptionFilter内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/97775b28859deb4f1f1d243920433cf1.html