【问题标题】:Swagger UI displaying the asp.net webapi parameter name with dot notationSwagger UI 显示带有点符号的 asp.net webapi 参数名称
【发布时间】:2016-06-08 14:46:18
【问题描述】:

我已经为我的 asp.net webapi 配置了 Swagger,类似于下面显示的一个

[HttpGet]
[Route("search")]
public async Task<HttpResponseMessage> Get([FromUri]SearchCriteria searchCriteria)

当我看到 webapi 的 swagger 文档时,参数显示为

searchCriteria.sortField searchCriteria.sortDirection 依此类推……作为 sortField,sortDirection 是 SearchCriteria 的属性

如何获取没有object.propertyname格式的参数名称?

谁能帮助解决这个问题? 谢谢

【问题讨论】:

    标签: c# asp.net-web-api2 swagger swagger-ui swashbuckle


    【解决方案1】:

    这是一个OperationFilter,我曾经用来从查询参数中删除类名。

    public class ParameterFilter : IOperationFilter
    {
        private const string Pattern = @"^ # Match start of string
                    .*? # Lazily match any character, trying to stop when the next condition becomes true
                    \.  # Match the dot";
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (operation.parameters == null)
            {
                return;
            }
    
            foreach (var parameter in operation.parameters
                .Where(x => x.@in == "query" && x.name.Contains(".")))
            {
                parameter.name = Regex.Replace(
                    parameter.name,
                    Pattern, 
                    string.Empty, 
                    RegexOptions.IgnorePatternWhitespace);
            }
        }
    }
    

    像这样将它添加给你SwaggerConfig

    GlobalConfiguration.Configuration
        .EnableSwagger(c =>
            {
                // other settings omitted
                c.OperationFilter<ParameterFilter>();    
            }); 
    

    顺便说一句:正则表达式的灵感来自https://stackoverflow.com/a/7794128/502395

    【讨论】:

      【解决方案2】:

      我假设您使用的是 Swashbuckle。

      查看DocumentFiltersOperationFilters。您可以扩展 Swashbuckle 以在文档或操作级别进行干预以修改输出。

      通读Swashbuckle documentation,实现这两个接口中的任何一个都相当简单。

      【讨论】:

        【解决方案3】:

        当您将参数Name = "" 传递给FormUri 属性时,Swashbuckle 会以非限定形式生成参数名称,例如sortField 而不是 searchCriteria.sortField

        public async Task<HttpResponseMessage> Get([FromUri(Name = "")]SearchCriteria searchCriteria)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-08-30
          • 1970-01-01
          • 2020-12-22
          • 2023-04-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多