【问题标题】:Is it possible to set response Content-Type based on response HTTP code in ASP.NET Core (Swashbucle)?是否可以根据 ASP.NET Core (Swashbucle) 中的响应 HTTP 代码设置响应 Content-Type?
【发布时间】:2019-10-30 14:09:56
【问题描述】:

我目前正在使用 Swashbuckle.AspNetCore 在 ASP.NET Core 3.0 上进行此工作,但我想知道 OpenAPI 3.0 Specification 的情况,以防其他人更清楚。

我目前尝试使用 Nuget 库设置规范,以便通常返回值是 content-type: application/json,但在特殊情况下是 content-type: application/problem+json。这在 ASP.NET Core 3.0 和 Swashbuckle 中似乎不可能开箱即用(或者我非常想念它)。它是否正确?如果不是开箱即用,有什么方法可以系统地做到这一点?

在 OpenAPI 规范中有可能吗?我倾向于相信它可能是,但在尝试浏览规范时错过了它。

这是自动生成的文档和 HTTP 400 案例的图像,我只想显示 application/problem+json 作为返回值。

【问题讨论】:

    标签: asp.net-core openapi swashbuckle


    【解决方案1】:

    这可以通过 IOperationFilter 来完成,您可以像下面这样自定义:

    1.CustomResponseType:

    using Microsoft.OpenApi.Models;
    using Swashbuckle.AspNetCore.SwaggerGen;
    using System.Collections.Generic;    
    public class CustomResponseType : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            if (operation.Responses.ContainsKey("400")) {
                operation.Responses.Clear();
            }
            var data = new OpenApiResponse
            {
                Description = "Bad Request",
                Content = new Dictionary<string, OpenApiMediaType>
                {
                    ["application/problem+json"] = new OpenApiMediaType(),
                }
            };
            operation.Responses.Add("400", data);
        }
    }
    

    2.Startup.cs:

    services.AddSwaggerGen(c =>
         {
              c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
              c.OperationFilter<CustomResponseType>();
         });
    

    3.结果:

    【讨论】:

    • 我倾向于接受这一点,但让我在大约四个小时后先上电脑。发生的一个问题,您是否碰巧知道这个IOperationFilter 是否可以在调用站点(在这种情况下在控制器中)作为代码构造(不是 cmets 等,这总比没有好)可见?这样会更清楚,但如果不可能的话,我很感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 2015-11-02
    • 2023-04-07
    • 1970-01-01
    • 2021-02-19
    • 2011-02-03
    相关资源
    最近更新 更多