例如,考虑一个带有 :
的 APIvar builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(o => o.OperationFilter<CustomFilter>());
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.MapGet("/", () => { }).WithOpenApi();
app.Run();
此 API 可以返回内容类型为
application/json
和 application/xml
的响应。
我想创建一个自定义
OperationFilter
来生成具有 API 内容类型可能性的 OpenApi 响应 :
public class Foo { }
public class CustomFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var schema = context.SchemaGenerator.GenerateSchema(typeof(Foo), context.SchemaRepository);
operation.Responses.Clear();
var response = new OpenApiResponse();
var apiResponseTypes = new[] { "application/json", "application/xml" }; // <- How get this from API metadata?
foreach(string responseType in apiResponseTypes)
{
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);
}
}