五类:Authorization Filter、 Resource Filter、 Action Filter 、Exception Filter 、Result Filter
新建文件:CustomExecptionFilterAttribute.cs
public class CustomExecptionFilterAttribute : ExceptionFilterAttribute
{
/// <summary>
/// 当异常发生时 进来处理
/// </summary>
/// <param name="context"></param>
public override void OnException(ExceptionContext context)
{
if (!context.ExceptionHandled)//当异常未处理
{
Console.WriteLine($"{context.HttpContext.Request.Path} {context.Exception.Message}");
context.Result = new JsonResult(new
{
Result = false,
Msg = "发生异常,请联系管理员"
});
context.ExceptionHandled = true;//异常标记-》已处理
}
}
}
Filter三种注册方式:
- [CustomExecptionFilterAttribute] Action注册--》 仅方法生效
- [CustomExecptionFilterAttribute] Controller注册--》仅控制器生效
- 全局注册 Startup--ConfigureServices --》全局生效
services.AddControllersWithViews(
option =>
{
option.Filters.Add(typeof(CustomExecptionFilterAttribute));//全局注册--错误处理
}
);
404错误是住不到的
AOP好处:
- 聚焦业务逻辑,轻松扩展功能
- 代码复用,集中管理
进阶需求:错误日志想要记录在txt日志文件里
public class CustomExecptionFilterAttribute : ExceptionFilterAttribute
{
private readonly ILogger<CustomExecptionFilterAttribute> _logger;
public CustomExecptionFilterAttribute(ILogger<CustomExecptionFilterAttribute> logger)
{
_logger = logger;
}
/// <summary>
/// 当异常发生时 进来处理
/// </summary>
/// <param name="context"></param>
public override void OnException(ExceptionContext context)
{
if (!context.ExceptionHandled)//当异常未处理
{
Console.WriteLine($"{context.HttpContext.Request.Path} {context.Exception.Message}");
_logger.LogError($"{context.HttpContext.Request.Path} {context.Exception.Message}");
context.Result = new JsonResult(new
{
Result = false,
Msg = "发生异常,请联系管理员"
});
context.ExceptionHandled = true;//异常标记-》已处理
}
}
}
CustomExecptionFilterAttribute是一个特性,特性是编译时确定的,构造函数只能传递常量,不能传递变量;
Filter注入方式:
- 全局注册 Startup--ConfigureServices 自动注入 控制器不需要注册
- [ServiceFilter(typeof(CustomExecptionFilterAttribute))] 控制器注入+Startup-》ConfigureServices (services.AddTransient<CustomExecptionFilterAttribute>();//注册)
- [TypeFilter(typeof(CustomExecptionFilterAttribute))] 控制器注入
- IFilterFactory
若文章有错误,请评论或者私信指出,谢谢