例如,带有以下内容的 API:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers().AddXmlSerializerFormatters();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options => options.OperationFilter<CustomFilter>());
此 API 可以返回内容类型为
application/json
和 application/xml
的响应。
我想创建一个自定义
OperationFilter
来生成具有 API 内容类型可能性的 OpenApi 响应 :
public class CustomFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var schema = context.SchemaGenerator.GenerateSchema(typeof(WeatherForecast), context.SchemaRepository);
operation.Responses.Clear();
var response = new OpenApiResponse();
foreach (string responseType in /*<api's response types>*/)
{
response.Content.Add(responseType, new OpenApiMediaType { Schema = schema });
}
operation.Responses.Add("200", response);
}
}
如何检索OperationFilter中的API响应内容类型?
要在自定义
OperationFilter
中检索 API 响应内容类型,您可以从操作方法的属性访问 ProducesAttribute
。
public class CustomFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var schema = context.SchemaGenerator.GenerateSchema(typeof(WeatherForecast), context.SchemaRepository);
operation.Responses.Clear();
var response = new OpenApiResponse();
// Get the ProducesAttribute from the action method
var producesAttribute = context.MethodInfo.GetCustomAttribute<ProducesAttribute>();
if (producesAttribute != null)
{
foreach (var responseType in producesAttribute.ContentTypes)
{
response.Content.Add(responseType, new OpenApiMediaType { Schema = schema });
}
}
operation.Responses.Add("200", response);
}
}