将 Content-Type 添加到 Swashbuckle 获取请求

Adding the Content-Type to the Swashbuckle Get Request

我使用 Swashbuckle 5.0 和 .Net Core 3.1

有一个 Get 方法能够 return 不同格式的结果(JSON 和 XML)。

我了解到最新版本的 Swagger 应该能够解析这段代码

    [HttpGet]
    [Produces("application/json", "application/xml")]
    public async Task<IActionResult> Get()
    {
        var model = new MyModel();
        return Ok(model);
    }

并生成适当的 Swagger 配置,最后在 UI.

中有类似 的内容

但是这段代码不知何故不起作用。我是否遗漏了什么,或者这只是最新版本 Swashbuckle 的错误,我应该采取一些解决方法吗?

更新(感谢 Jawad): 我的格式化程序启动配置如下所示:

services.AddControllers(options => 
{
    options.RespectBrowserAcceptHeader = true;
})
.AddXmlSerializerFormatters()
.AddXmlDataContractSerializerFormatters()
.AddNewtonsoftJson(opt => { opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; });

我不太确定为什么会有 2 个 XML 格式化程序(可能是一些合并问题),但直到这一刻它才起作用。

确保将 SupportedMediaTypes 添加到 WebApiConfig.cs 文件中,

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));

似乎 Swagger UI 仅在 return 类型已知时才显示媒体类型。由于您正在 returning ActionResult,Swashbuckle 不知道 return 类型是什么。 当我将控制器更改为

public async Task<T> Get()

或添加属性

[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(T))]

我能够在我的应用程序中看到不同的响应内容类型