asp.net-core - 如何在 asp.net core 2.2 中更改 api 返回结果?
问题描述
我的要求是当操作的返回类型为 void 或 Task 时,我想返回我的自定义ApiResult
。我尝试了中间件机制,但我观察到的响应对于 ContentLength 和 ContentType 都为 null,而我想要的是 .json 的空实例的 json 表示ApiResult
。那我应该在哪里进行这种转换?
解决方案
.net core 中有多个过滤器,你可以试试Result filters。
对于void
or Task
,它将返回EmptyResult
in OnResultExecutionAsync
。
尝试实现自己的ResultFilter
喜欢
public class ResponseFilter : IAsyncResultFilter
{
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
// do something before the action executes
if (context.Result is EmptyResult)
{
context.Result = new JsonResult(new ApiResult());
}
var resultContext = await next();
// do something after the action executes; resultContext.Result will be set
}
}
public class ApiResult
{
public int Code { get; set; }
public object Result { get; set; }
}
并将其注册到Startup.cs
services.AddScoped<ResponseFilter>();
services.AddMvc(c =>
{
c.Filters.Add(typeof(ResponseFilter));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
推荐阅读
- wordpress - 由 paginate_links() 回显的分页未显示在 page.php 中
- javascript - 如何计算单击特定 dom 元素时随后发送的多个 Ajax 请求的响应时间
- sql - 根据 SQL 中的条件在行上存储数据
- c# - C# 中方法和函数的意义何在?
- javascript - 避免数据库重复数据
- python - 如果条件因未知原因而失败
- c - 堆栈头部和尾部更新为相同的值,但仅在 head-C 编程上调用更新
- python - 循环嵌套列表?
- c++ - 如何在 Visual Studio 中制作 Qt Quick 应用程序?
- vue.js - 如何强制 VueJ 在将大量数据加载到 DOM 之前/之后显示/隐藏元素?