无良二少在洪荒,情感小文章,优膳房
.net core中有各种filter,分别是authorizationfilter、resourcefilter、exceptionfilter、actionfilter、resultfilter。可以把他们看作是.net core自带的aop的扩展封装。
今天来看其中的一种:exceptionfilter(用于全局的异常处理)
首先新建一个.net core mvc的项目
新建一个控制器:
这里我们可以看到代码运行到16行时会报一个索引项超出集合范围的错误
按照常规的思维我们在代码中会加异常处理,如下:
try { var range = enumerable.range(1, 3).toarray(); var result = range[4]; return view(); } catch (exception ex) { throw new exception(ex.message); }
但是每个方法都这样加会不会觉得很烦?有没有想过只写一次就可以了
上代码:
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;//异常已处理 } } } }
我们在方法中先以特性来使用,加上这句代码:
[typefilter(typeof(customerexceptionfilter))]
之后会跳到这个视图:../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内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Net Core Web Api项目与在NginX下发布的方法
asp.net core3.1 引用的元包dll版本兼容性问题解决方案
IdentityServer4实现.Net Core API接口权限认证(快速入门)
ASP.NET Core MVC通过IViewLocationExpander扩展视图搜索路径的实现
网友评论