【发布时间】: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
我尝试使用MapType 和ISchemaFilter 如下:
// 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