是否可以根据 ASP.NET Core (Swashbucle) 中的响应 HTTP 代码设置响应 Content-Type?
Is it possible to set response Content-Type based on response HTTP code in ASP.NET Core (Swashbucle)?
我目前正在使用 Swashbuckle.AspNetCore, but I would like to know the case for OpenAPI 3.0 Specification 在 ASP.NET Core 3.0 上工作,以防其他人知道得更多。
我目前尝试使用 Nuget 库设置规范,以便通常 return 值为 content-type: application/json
,但在特殊情况下 content-type: application/problem+json
。这在 ASP.NET Core 3.0 和 Swashbuckle 中似乎不可能开箱即用(或者我非常想念它)。这个对吗?如果不是开箱即用,系统地执行此操作的方法是什么?
在 OpenAPI 规范中是否可行?我倾向于相信它可能是,但在试图浏览规范时错过了它。
这是自动生成的文档和 HTTP 400 案例的图像我只想显示 application/problem+json
作为 return 值。
这可以通过 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.Result:
我目前正在使用 Swashbuckle.AspNetCore, but I would like to know the case for OpenAPI 3.0 Specification 在 ASP.NET Core 3.0 上工作,以防其他人知道得更多。
我目前尝试使用 Nuget 库设置规范,以便通常 return 值为 content-type: application/json
,但在特殊情况下 content-type: application/problem+json
。这在 ASP.NET Core 3.0 和 Swashbuckle 中似乎不可能开箱即用(或者我非常想念它)。这个对吗?如果不是开箱即用,系统地执行此操作的方法是什么?
在 OpenAPI 规范中是否可行?我倾向于相信它可能是,但在试图浏览规范时错过了它。
这是自动生成的文档和 HTTP 400 案例的图像我只想显示 application/problem+json
作为 return 值。
这可以通过 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.Result: