Asp.net core mvc Swashback通用响应代码

Asp.net core mvc Swashback通用响应代码,asp.net-core-mvc,swagger,swashbuckle,Asp.net Core Mvc,Swagger,Swashbuckle,是否有办法定义适用于所有呼叫的“通用”响应代码 例如,所有呼叫都可以返回以下其中一个: 400 - Bad request 500 - Internal server error (unknown exception occurred) 503 - Service unavailable (maintenance mode) 与其复制粘贴每个端点上的注释和属性,不如在某个中心位置定义它。谢谢@HelderSepu确实IDocumentFilter是解决方案 //招摇过市配置 swagger.D

是否有办法定义适用于所有呼叫的“通用”响应代码

例如,所有呼叫都可以返回以下其中一个:

400 - Bad request
500 - Internal server error (unknown exception occurred)
503 - Service unavailable (maintenance mode)

与其复制粘贴每个端点上的注释和属性,不如在某个中心位置定义它。

谢谢@HelderSepu确实IDocumentFilter是解决方案

//招摇过市配置
swagger.DocumentFilter();
内部类DefaultFilter:IDocumentFilter
{
公共无效应用(SwaggerDocument swaggerDoc、DocumentFilterContext上下文)
{
foreach(swaggerDoc.path.Values中的变量项)
{
更新项(项目“400”,“错误或格式错误的请求”);
更新项(项目“500”,“内部服务器错误”);
更新项(项目“503”,“维护模式下的服务”);
}
}
私有静态void UpdateItem(路径项、字符串键、字符串描述)
{
TrySetValue(item.Get、key、description);
TrySetValue(项、输入、键、描述);
}
私有静态void TrySetValue(操作op、字符串键、字符串描述)
{
if((op==null)| |(op.Responses.ContainsKey(key)))
{
返回;
}
op.Responses.Add(键,新响应
{
描述=描述,
});
}
}

适用于任何使用Swashback 5的人

//在AddSwaggerGen中
c、 操作过滤器();
内部类GeneralExceptionOperationFilter:IOperationFilter
{
公共无效应用(OpenApiOperation操作,OperationFilterContext上下文)
{
Add(“401”,新OpenApiResponse(){Description=“Unauthorized”});
Add(“403”,新的OpenApiResponse(){Description=“probled”});
//我们筛选特定HttpMethod并定义返回模型的示例
var method=context.MethodInfo.GetCustomAttributes(true)
第()类
.Single();
如果(方法是HttpDeleteAttribute | |方法是HttpPostAttribute | |方法是HttpPatchAttribute | |方法是HttpPutAttribute)
{
operation.Responses.Add(“409”,新的OpenApiResponse()
{
Description=“Conflict”,
Content=新字典()
{
[“应用程序/json”]=新的OpenApiMediaType
{
Schema=context.SchemaGenerator.GenerateSchema(typeof(string),context.SchemaRepository)
}
}
});
}
}
}

您查看过IDocumentFilters吗?\u我喜欢它!很高兴看到你可以在正确的方向上轻轻推一下!这里的很多人都想得到一个完整的复制/粘贴解决方案,现在对于示例答案,请保持简短,不需要把所有的操作放在一对夫妇身上就足够了,与TrySetValue相同,您不需要IF,让复制粘贴者自己来计算