查看原文
其他

.NET Core中使用ExceptionFilter

DotNet 2021-09-23

(给DotNet加星标,提升.Net技能

转自: 江北、
cnblogs.com/zhangnever/p/12397117.html

前言


.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();


 End!


推荐阅读  点击标题可跳转
奉上简单的.NET后端开发模板.NET Core微服务架构实践ASP.NET Core高性能Span<T>和Memory<T>


看完本文有收获?请转发分享给更多人

关注「DotNet」加星标,提升.Net技能 

好文章,我在看❤️

: . Video Mini Program Like ,轻点两下取消赞 Wow ,轻点两下取消在看

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存