[英]How to expose a custom generic type as a string in Swagger schema using Swashbuckle.AspNetCore
[英]How to replace generic type to concrete type when generating Swagger documentation with Swashbuckle?
我的動作裝飾有:
[ProducesResponseType(typeof(ValidationException<ErrorEnum>), StatusCodes.Status400BadRequest)]
我需要將生成的響應更改為不同的類型。 所以我添加了一個操作過濾器:
public class ValidationExceptionFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (context.ApiDescription.ActionDescriptor is ControllerActionDescriptor cad)
{
var returnType = cad.MethodInfo.ReturnType;
if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(ValidationException<>))
{
var schema = context.SchemaGenerator.GenerateSchema(typeof(ValidationExceptionDto), context.SchemaRepository);
foreach (var item in operation.Responses["400"].Content)
item.Value.Schema = schema;
}
}
}
}
但是生成 swagger json 時通用類型沒有被替換。我在這里缺少什么?
使用此行,您將獲得方法的返回類型:
var returnType = cad.MethodInfo.ReturnType;
例如,A controller 像:
[HttpGet]
[ProducesResponseType(400, Type = typeof(Some<WeatherForecast>))]
[ProducesResponseType(200, Type = typeof(WeatherForecast))]
public IEnumerable<WeatherForecast> Get()
{
.......
}
您將獲得 IEnumerable WeatherForecast 類型,而不是 Some 或 WeatherForecast 類型
我試圖在方法上獲取 ProducesResponseTypeAttribute 並訪問 Type 屬性:
public class ValidationExceptionFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (context.ApiDescription.ActionDescriptor is ControllerActionDescriptor cad)
{
var attrs=cad.MethodInfo.GetCustomAttributes(typeof(ProducesResponseTypeAttribute),true);
foreach(var attr in attrs)
{
if((attr as ProducesResponseTypeAttribute).Type.IsGenericType&& (attr as ProducesResponseTypeAttribute).Type.GetGenericTypeDefinition()==typeof(Some<>)) {
var schema = context.SchemaGenerator.GenerateSchema(typeof(SomeDto), context.SchemaRepository);
foreach (var item in operation.Responses["400"].Content)
item.Value.Schema = schema;
}
}
}
}
}
響應類型已修改:
json文件:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.