首页 > 解决方案 > 如何在 asp.net core 2.2 中更改 api 返回结果?

问题描述

我的要求是当操作的返回类型为 void 或 Task 时,我想返回我的自定义ApiResult。我尝试了中间件机制,但我观察到的响应对于 ContentLength 和 ContentType 都为 null,而我想要的是 .json 的空实例的 json 表示ApiResult。那我应该在哪里进行这种转换?

标签: asp.net-coreasp.net-core-2.2

解决方案


.net core 中有多个过滤器,你可以试试Result filters

对于voidor Task,它将返回EmptyResultin 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);

推荐阅读