.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過濾器的方法的文章就介紹到這了,更多相關.Net Core使用ExceptionFilter內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/zhangnever/p/12397117.html