Swashbuckle MapType<类型>不适用于参数不适用于、参数、类型、MapType

2023-09-08 09:22:35 作者:缠绵勾画

我有一个将 ShortGuid 类作为参数的 API 端点,如下所示:

I've got an API endpoint that takes a ShortGuid class as a parameter, like such:

[HttpGet("api/endpoint")]
public async Task<IActionResult> GetTablesAsync(ShortGuid id){}

生成一个大摇大摆的定义:

Generates a swagger definition of:

"parameters":[
    {
        "name":"guid",
        "in":"query",
        "required":false,
        "type":"string",
        "format":"uuid"
    },
    {
        "name":"value",
        "in":"query",
        "required":false,
        "type":"string"
    }
],

我需要将该参数视为字符串,而不是 ShortGuid 对象.我已经有一个可以正常工作的类型的 JsonConverter,但是 Swashbuckle 不理解它,所以我的架构不正确(而且我的 swagger-js 客户端不起作用).我认为 MapType 会起作用,但这似乎只影响响应对象,因为架构仍将其视为 ShortGuid.

I need to treat that parameter as a string, not a ShortGuid object. I already have a JsonConverter for the type that works fine, but Swashbuckle doesn't understand it so my schema is incorrect (and this my swagger-js client doesnt work). I thought MapType<> would work however that seems to only affect response objects as the schema still treats it as a ShortGuid.

c.MapType<ShortGuid>(() => new Schema { Type = "string" });

我需要一个 ISchemaFilter 来执行此操作吗?如果是这样,我该如何编写它(尝试了多次但没有成功)

Will I require an ISchemaFilter to do this? And if so, how do I go about writing it (tried multiple attempts but no success)

推荐答案

为此,您必须为您的 ShortGuid 添加一个 TypeConverter.

For this to work on the query string, you have to add a TypeConverter for your ShortGuid.

这里有一些关于为什么它不起作用的信息:https://github.com/dotnet/aspnetcore/issues/4825

Here is some information on why it does not work otherwise: https://github.com/dotnet/aspnetcore/issues/4825

另外请注意,如果您使用 Nullable,您还需要添加 c.MapType