.Net Core中使用ExceptionFilter

.Net Core中有各类Filter,分别是AuthorizationFilter、ResourceFilter、ExceptionFilter、ActionFilter、ResultFilter。能够把他们看做是.Net Core自带的AOP的扩展封装。html

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

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

新建一个控制器:spa

 这里咱们能够看到代码运行到16行时会报一个索引项超出集合范围的错误code

按照常规的思惟咱们在代码中会加异常处理,以下:htm

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

可是每一个方法都这样加会不会以为很烦?有没有想过只写一次就能够了blog

上代码:索引

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 ,会将异常信息传入到此视图it

视图页代码:

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

(能够自行封装。。。)

咱们还能够定义成全局的

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

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

 End!

原文出处:https://www.cnblogs.com/zhangnever/p/12397117.html

相关文章
相关标签/搜索