# ResultFilter 同步实现
public class CustomResultFilterAttribute : Attribute, IResultFilter | |
{ | |
public void OnResultExecuted (ResultExecutedContext context) | |
{ | |
Console.WriteLine ("结果过滤器之后"); | |
} | |
public void OnResultExecuting (ResultExecutingContext context) | |
{ | |
Console.WriteLine ("结果过滤器之前"); | |
} | |
} |
标注 action
[Route ("/api/[action]")] | |
public class ResultController:ControllerBase | |
{ | |
public ResultController () | |
{ | |
Console.WriteLine ("构造函数"); | |
} | |
[HttpGet] | |
[CustomResultFilterAttribute] | |
public string ResultIndex () | |
{ | |
Console.WriteLine ("方法执行"); | |
return "resultFilter"; | |
} | |
} |
# 运行项目
# 结论
控制器构造函数-》调用的API(action)-》OnResultExecuting-》OnResultExecuted
# ResultFilter 异步实现
public class CustomAsyncResultFilterAttribute : Attribute, IAsyncResultFilter | |
{ | |
public async Task OnResultExecutionAsync (ResultExecutingContext context, ResultExecutionDelegate next) | |
{ | |
Console.WriteLine ("结果过滤器之前"); | |
await next.Invoke (); | |
Console.WriteLine ("结果过滤器之后"); | |
} | |
} |
# ResultFilter 在业务上能用来做什么
对接口(action)中的结果进行处理。例如将返回的结果变成统一的json格式
处理之前的结果
public class CustomResultFilterAttribute : Attribute, IResultFilter | |
{ | |
public void OnResultExecuted (ResultExecutedContext context) | |
{ | |
Console.WriteLine ("结果过滤器之后"); | |
} | |
public void OnResultExecuting (ResultExecutingContext context) | |
{ | |
dynamic result = context.Result; | |
context.Result = new JsonResult (new Result | |
{ | |
Data=result.Value, | |
Code=200, | |
Msg="success" | |
}); | |
Console.WriteLine ("结果过滤器之前"); | |
} | |
} | |
public class Result | |
{ | |
public string Msg { get; set; } | |
public int Code { get; set; } | |
public object Data { get; set; } | |
} |
处理之后的结果