【问题标题】:Swashbuckle request parameters not working when using custom model binder使用自定义模型绑定器时 Swashbuckle 请求参数不起作用
【发布时间】:2020-08-13 15:37:04
【问题描述】:

我有一个 ASP.NET Core 3.1 API 端点配置如下:

[HttpGet("api/controller/action/{id}")]
public async Task<IActionResult> GetSingle([FromRoute] GetSingleRequest request) {...}

DTO 有一个 Guid 属性:

public class GetSingleRequest
{
  public Guid Id { get; set; }
}

我已经配置了一个自定义模型绑定器来将 Guid 属性绑定到字符串值,因为我正在使用一个简短的 guid 实现。使用 Postman 进行测试时,一切正常。

但是,在使用 Swagger 时,不是按照输入的方式传递路由参数,而是传递参数模板,例如

GET /api/controller/action/{id}     // Literally constructs the URI with {id}
GET /api/controller/action/abcd1234 // Not the value as entered

我尝试使用MapTypeISchemaFilter 如下:

// startup.cs
c.MapType<Guid>(() => new OpenApiSchema {Type = "string", Format = null});
// startup.cs
c.SchemaFilter<GuidSchemaFilter>();

// GuidSchemaFilter.cs
internal class GuidSchemaFilter : ISchemaFilter
  {
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
      if (context.Type != typeof(Guid))
      {
        return;
      }

      schema.Type = "string";
      schema.Format = null;
    }
  }

这些方法都没有改变这种奇怪的行为。

当我配置了自定义模型绑定器时,如何配置 Swagger 以将字符串而不是 Guid 作为 URI 的一部分传递?

【问题讨论】:

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


    【解决方案1】:

    如何配置 Swagger 以传递字符串而不是 Guid 作为一部分 当我配置了自定义模型绑定器时的 URI?

    其实c.MapType&lt;Guid&gt;(() =&gt; new OpenApiSchema {Type = "string", Format = null});这句话就足够解决问题了。

    问题的关键在于你的路由中的参数是Camel Case:id,而GetSingleRequest中的字段是Pascal Case:Id

    作为注释,可以添加c.DescribeAllParametersInCamelCase();,使其忽略大小写问题。

      services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API" });
                    c.MapType<Guid>(() => new OpenApiSchema { Type = "string", Format = null });
                    c.DescribeAllParametersInCamelCase();
                }); 
    

    或者你把路由模板中的id改成Id

            [HttpGet("api/controller/action/{Id}")]
            public async Task<IActionResult> GetSingle([FromRoute] GetSingleRequest request) 
            {
    
                return Ok();
            }
    

    这是测试结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-10
      • 2012-07-31
      • 2015-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多