C#虚张声势

C#虚张声势,c#,asp.net-web-api,attributes,swagger,C#,Asp.net Web Api,Attributes,Swagger,我有一个WebApi项目,我正在尝试实现Swagger。我正在使用Swahbuckle(5.2.1)。 在我的实际项目中,我的回答已经有了一个属性: [responsefrapi(HttpStatusCode.OK)] 我的问题是我使用的是Swashback(5.2.1),我不想为我的方法添加其他属性。我知道如何将响应放在Swagger上,我可以使用“XML注释”或属性: [SwaggerResponse(HttpStatusCode.OK)] 我的问题是:有没有一种方法可以通过调用“Respo

我有一个WebApi项目,我正在尝试实现Swagger。我正在使用Swahbuckle(5.2.1)。 在我的实际项目中,我的回答已经有了一个属性:

[responsefrapi(HttpStatusCode.OK)]

我的问题是我使用的是Swashback(5.2.1),我不想为我的方法添加其他属性。我知道如何将响应放在Swagger上,我可以使用“XML注释”或属性:

[SwaggerResponse(HttpStatusCode.OK)]


我的问题是:有没有一种方法可以通过调用“ResponseFrapi”来使用“SwaggerResponse”?

你可以通过基于ApplySwaggerResponseAttributes连接自己的IOperationFilter来实现这一点——这是扫描[SwaggerResponse]的东西。这是我根据虚张声势的密码设计的

公共类ApplyResponseTypeAttribute:IOperationFilter
{
public void Apply(操作,SchemaRegistry SchemaRegistry,apisdescription apisdescription)
{
if(apisdescription.GetControllerAndActionAttributes().Any())
{
operation.responses.Clear();
}
//大摇大摆的回应颂词胜过回应颂词
var swaggerAttributes=apiscription.GetControllerAndActionAttributes();
如果(!swaggerAttributes.Any())
{
var responseAttributes=apiscription.GetControllerAndActionAttributes().OrderBy(attr=>attr.ResponseType.Name);
foreach(响应属性中的var attr)
{
常量字符串StatusCode=“200”;
操作.响应[状态代码]=新响应
{
描述=推断描述来源(状态代码),
schema=(attr.ResponseType!=null)?schemaRegistry.GetOrRegister(attr.ResponseType):null
};
}
}
}
私有字符串推断描述源(字符串状态代码)
{
HttpStatusCode枚举值;
if(Enum.TryParse(statusCode、true、out enumValue))
{
返回enumValue.ToString();
}
返回null;
}
}
在./App_Start中的招摇过市配置中,添加以下内容以注册此筛选器。在上面设置一个断点是非常有趣的,这样你就可以看到Swashback是如何工作的,它会迭代你的控制器的所有动作

c.OperationFilter<ApplyResponseTypeAttributes>();
c.操作过滤器();
c.OperationFilter<ApplyResponseTypeAttributes>();