我有一个WebApi项目,我正在尝试实现Swagger。我使用的是斯瓦巴克尔(5.2.1)。在我的实际项目中,我的响应已经有了一个属性:
[ResponseForApi(HttpStatusCode.OK)]
我的问题是我正在使用Swashbuckle (5.2.1),并且我不想为我的方法添加其他属性。我知道如何将响应放到Swagger上,我可以使用“XML Comments”或以下属性:
[SwaggerResponse(HttpStatusCode.OK)]
我的问题是:有没有办法通过调用'ResponseForApi‘来使用'SwaggerResponse’?
发布于 2015-12-08 12:50:29
您可以通过基于ApplySwaggerResponseAttributes连接您自己的IOperationFilter来做到这一点--这是扫描SwaggerResponse的东西。下面是我基于Swashbuckle代码https://github.com/domaindrivendev/Swashbuckle/blob/master/Swashbuckle.Core/Swagger/Annotations/ApplySwaggerResponseAttributes.cs创建的代码
public class ApplyResponseTypeAttributes : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (apiDescription.GetControllerAndActionAttributes<SwaggerResponseRemoveDefaultsAttribute>().Any())
{
operation.responses.Clear();
}
// SwaggerResponseAttribute trumps ResponseTypeAttribute
var swaggerAttributes = apiDescription.GetControllerAndActionAttributes<SwaggerResponseAttribute>();
if (!swaggerAttributes.Any())
{
var responseAttributes = apiDescription.GetControllerAndActionAttributes<ResponseTypeAttribute>().OrderBy(attr => attr.ResponseType.Name);
foreach (var attr in responseAttributes)
{
const string StatusCode = "200";
operation.responses[StatusCode] = new Response
{
description = InferDescriptionFrom(StatusCode),
schema = (attr.ResponseType != null) ? schemaRegistry.GetOrRegister(attr.ResponseType) : null
};
}
}
}
private string InferDescriptionFrom(string statusCode)
{
HttpStatusCode enumValue;
if (Enum.TryParse(statusCode, true, out enumValue))
{
return enumValue.ToString();
}
return null;
}
}在./App_Start中的swagger配置中,添加以下内容以注册此过滤器。实际上,在上面设置一个断点非常有趣,这样你就可以看到Swashbuckle是如何工作的,它会遍历你控制器的所有动作。
c.OperationFilter<ApplyResponseTypeAttributes>();https://stackoverflow.com/questions/32497075
复制相似问题