如何在 swagger UI 中使用 Swashbuckle 设置内容类型 application/json 和 application/xml
How to set the content type application/json and application/xml using Swashbuckle in swagger UI
您好,我正在使用 Swashbuckle
我想为请求和响应负载设置内容类型“application/json 和 application/xml”。任何人都可以帮助我如何根据我的喜好设置内容类型。
我已经尝试过这段代码,它适用于请求而不是响应。
[HttpPost]
[Consumes(MediaTypeNames.Application.Json)]
[SwaggerResponse(200,null,typeof(Logs))]
[SwaggerResponse(400, null, typeof(Logs))]
public async Task<IActionResult> PostAsync()
要配置响应的内容类型,您可以使用过滤器:
public class SwaggerMediaTypesOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
foreach (var key in operation.Responses.Keys)
{
FilterMediaTypes(operation.Responses[key].Content);
}
if (operation.RequestBody?.Content != null)
{
FilterMediaTypes(operation.RequestBody.Content);
}
}
private static void FilterMediaTypes(IDictionary<string, OpenApiMediaType> apiMediaTypes)
{
if (apiMediaTypes.TryGetValue(MediaTypeNames.Application.Json, out OpenApiMediaType applicationJson))
{
apiMediaTypes.Clear();
apiMediaTypes.Add(MediaTypeNames.Application.Json, applicationJson);
apiMediaTypes.Add(MediaTypeNames.Application.Xml, applicationJson);
}
}
}
然后,
services.AddSwaggerGen(cfg =>
{
cfg.OperationFilter<SwaggerMediaTypesOperationFilter>();
...
};
您好,我正在使用 Swashbuckle 我想为请求和响应负载设置内容类型“application/json 和 application/xml”。任何人都可以帮助我如何根据我的喜好设置内容类型。 我已经尝试过这段代码,它适用于请求而不是响应。 [HttpPost]
[Consumes(MediaTypeNames.Application.Json)]
[SwaggerResponse(200,null,typeof(Logs))]
[SwaggerResponse(400, null, typeof(Logs))]
public async Task<IActionResult> PostAsync()
要配置响应的内容类型,您可以使用过滤器:
public class SwaggerMediaTypesOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
foreach (var key in operation.Responses.Keys)
{
FilterMediaTypes(operation.Responses[key].Content);
}
if (operation.RequestBody?.Content != null)
{
FilterMediaTypes(operation.RequestBody.Content);
}
}
private static void FilterMediaTypes(IDictionary<string, OpenApiMediaType> apiMediaTypes)
{
if (apiMediaTypes.TryGetValue(MediaTypeNames.Application.Json, out OpenApiMediaType applicationJson))
{
apiMediaTypes.Clear();
apiMediaTypes.Add(MediaTypeNames.Application.Json, applicationJson);
apiMediaTypes.Add(MediaTypeNames.Application.Xml, applicationJson);
}
}
}
然后,
services.AddSwaggerGen(cfg =>
{
cfg.OperationFilter<SwaggerMediaTypesOperationFilter>();
...
};