c# - 手动设置 operationId 以允许在 Swashbuckle 中使用同一个动词进行多个操作

标签 c# asp.net-web-api swagger asp.net-web-api-routing swashbuckle

我需要知道是否可以设置自定义 operationid 或命名约定,我的意思是我知道可以按照生成 operationId 的方式覆盖操作过滤器

https://azure.microsoft.com/en-us/documentation/articles/app-service-api-dotnet-swashbuckle-customize/

using Swashbuckle.Swagger;
using System.Web.Http.Description;

namespace Something
{
    public class MultipleOperationsWithSameVerbFilter : IOperationFilter
    {
        public void Apply(
            Operation operation,
            SchemaRegistry schemaRegistry,
            ApiDescription apiDescription)
        {
            if (operation.parameters != null)
            {
                operation.operationId += "By";
                foreach (var parm in operation.parameters)
                {
                    operation.operationId += string.Format("{0}",parm.name);
                }
            }
        }
    }
}

在 SwaggerConfig.cs 中

 c.OperationFilter<MultipleOperationsWithSameVerbFilter>();

现在这有助于转换 swagger 描述,检查以下内容:

enter image description here

很好,现在我遇到了另一个问题,示例类似于可能的情况:在同一个 Controller 上我有两个端点

  • 职位:/customer boddy:{电子邮件、位置....}
  • Post:/customer/search boddy: {过滤器,随便什么}

该示例不太正确(最后一篇文章应该是一个 get)但仍然假设对于这种特殊情况不能更改 webapi(用于分离的新 Controller )我将尝试找出一种方法来为每个生成不同的 operationId以某种方式采取行动,但我的问题是:

Is it possible to decorate somehow the controller actions similar with [JsonIgnore] or with [Route("customer/delete")], to be explicit about the operationId.

最佳答案

编辑 这个答案与 Swashbuckle 5.6 和 .NET Framework 相关。请阅读mwilson's answer用于 Swashbuckle 和 .NET Core

为此,您可以使用 Swashbuckle 提供的 SwaggerOperationAttribute

[SwaggerOperation("get")]
public IEnumerable<Contact> Get()
{
    ....
}

[SwaggerOperation("getById")]
public IEnumerable<Contact> Get(string id)
{
    ...
}

顺便说一句,您也可以使用该属性为您的操作添加标签和方案。看看 source code

关于c# - 手动设置 operationId 以允许在 Swashbuckle 中使用同一个动词进行多个操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39412998/

相关文章:

c# - StatusCodeResult 或 ResponseMessageResult

Swagger API特殊字符问题

c# - 一键打印多个 PDF 文件

c# - 如何编写 Web Api 单元测试,我应该从 UserManager 获取信息

c# - 为 JVM 实现 C#

c# - 从 WebAPI 调用返回 Sitecore 媒体项目

java - spring boot swagger中手动指定POST请求体

python - 如何从 Django 内置 API 文档中排除 rest-auth 端点?

c# - 实体通用分页

javascript - ASP.NET 获取页面加载时的窗口大小