.Net Core AlwaysRunResultFilter

作用

  1. 修改返回值,始终会触发,即使filter已经中断也会执行AlwaysRunFilter
  2. 任何时刻都会执行一遍, 可以在做了缓存的时候(如果有缓存并中断了,只有AlwaysRunFilter会执行),将一部3. 分查数据库的数据添加进去
  3. 返回前触发一次
  4. 返回后触发一次

如果都设置执行顺序为:

  1. ResultExecutingContext
  2. 返回值 (ActionResult)
  3. ResultExecutedContext

实现

IAlwaysRunResultFilter

  1. 需要继承 Attribute 并实现 IAlwaysRunResultFilter
  2. 实现接口方法

执行顺序为:

  1. OnResultExecutionAsync
  2. 返回值
  3. ResultExecutedContext

IAsyncAlwaysRunResultFilter

  1. 需要继承 Attribute并实现 IAsyncAlwaysRunResultFilter
  2. 实现接口方法
  3. 该接口只提供一个 OnResultExecutionAsync方法,如果想执行ResultExecutedContext方法,需要执行方法中ResultExecutionDelegate委托并取返回值然后代码在执行为ResultExecutedContext方法

执行顺序为:

  1. OnResultExecutionAsync
  2. 返回值
  3. 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();
posted @ 2023-08-03 22:57  qfccc  阅读(33)  评论(0编辑  收藏  举报