目录
作用
- 修改返回值,始终会触发,即使filter已经中断也会执行AlwaysRunFilter
- 任何时刻都会执行一遍, 可以在做了缓存的时候(如果有缓存并中断了,只有AlwaysRunFilter会执行),将一部3. 分查数据库的数据添加进去
- 返回前触发一次
- 返回后触发一次
如果都设置执行顺序为:
- ResultExecutingContext
- 返回值 (ActionResult)
- ResultExecutedContext
实现
IAlwaysRunResultFilter
- 需要继承 Attribute 并实现 IAlwaysRunResultFilter
- 实现接口方法
执行顺序为:
- OnResultExecutionAsync
- 返回值
- ResultExecutedContext
IAsyncAlwaysRunResultFilter
- 需要继承 Attribute并实现 IAsyncAlwaysRunResultFilter
- 实现接口方法
- 该接口只提供一个 OnResultExecutionAsync方法,如果想执行ResultExecutedContext方法,需要执行方法中ResultExecutionDelegate委托并取返回值然后代码在执行为ResultExecutedContext方法
执行顺序为:
- OnResultExecutionAsync
- 返回值
- ResultExecutedContext
Demo
CustomAsyncAlwaysRunResultFilterAttribute.cs
sing Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Cnpc.Com.Ioc.WebApp.Filter.AlwaysRunFilter
{
public class CustomAsyncAlwaysRunResultFilterAttribute : Attribute, IAsyncAlwaysRunResultFilter
{
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
{
JsonResult json = (JsonResult)context.Result; //修改返回值并在基础上增加新的数据
context.Result = new JsonResult(new
{
sussces = true,
httpStatus = 200,
result = json.Value
});
}
ResultExecutedContext executed = await next();
{
Console.WriteLine("ResultExecutedContext");
}
}
}
}
全局注册
Program.cs
builder.Services.AddControllersWithViews(
options =>
{
//这样注册将对所有action 都生效
options.Filters.Add<CustomAsyncAlwaysRunResultFilterAttribute>();
}).AddControllersAsServices();
标签:OnResultExecutionAsync,Core,AlwaysRunFilter,ResultExecutedContext,AlwaysRunResul
From: https://www.cnblogs.com/qfccc/p/17602241.html