.Net Core中有各類Filter,分別是AuthorizationFilter、ResourceFilter、ExceptionFilter、ActionFilter、ResultFilter。能夠把他們看做是.Net Core自帶的AOP的擴展封裝。async
今天來看其中的一種:ExceptionFilter(用於全局的異常處理)ide
首先新建一個.Net Core MVC的項目spa
新建一個控制器:code
這裏咱們能夠看到代碼運行到16行時會報一個索引項超出集合範圍的錯誤blog
按照常規的思惟咱們在代碼中會加異常處理,以下:索引
try { var range = Enumerable.Range(1, 3).ToArray(); var result = range[4]; return View(); } catch (Exception ex) { throw new Exception(ex.Message); }
可是每一個方法都這樣加會不會以爲很煩?有沒有想過只寫一次就能夠了開發
上代碼:it
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;//異常已處理 } } } }
咱們在方法中先以特性來使用,加上這句代碼:io
[TypeFilter(typeof(CustomerExceptionFilter))]
以後會跳到這個視圖:../Handle/Index ,會將異常信息傳入到此視圖class
視圖頁代碼:
<p>Message:@ViewData["Exception"]</p>
(能夠自行封裝。。。)
咱們還能夠定義成全局的
在Startup類中的ConfigureServices方法中加入這句代碼
services.AddControllersWithViews(option => { option.Filters.Add<CustomerExceptionFilter>(); });
//3.0如下的版本好像應該這樣寫:services.AddMvc();
End!