如何将自定义模型活页夹与Swashbuckle,Swagger和NSwag一起使用?

Ray*_*lli 8 c# swagger swashbuckle asp.net-core nswag

我有一个包含以下端点的ASP.NET Core Web API。

[HttpGet]
[Route("models/{ids}")]
[Produces(typeof(IEnumerable<Model>))]
public IActionResult Get
(
    [ModelBinder(typeof(CsvModelBinder<string>))] IEnumerable<string> ids
)
{
    // Get models

    return Ok(models);
}
Run Code Online (Sandbox Code Playgroud)

该端点获取一个ID的CSV列表(例如/models/a,b,c),并返回相应Model对象的JSON数组。 CsvModelBinder<string>IModelBinder我编写的自定义实现,该实现将Ids的CSV列表拆分为IEnumerable<string>,我可以在查询中使用它来查找对象。这一切都很好。

我现在想做的是使用NSwag生成客户端库,但这被证明是有问题的,因为Swashbuckle生成的Swagger将ids参数描述为IEnumerable<string>,而不是string

选项A:有没有办法告诉Swashbuckle将参数描述为a string而不是as IEnumerable<string>

选项B:有没有办法告诉NSwag IEnumerable<string>在生成请求URL时应将此参数编组为CSV?

Ray*_*lli 6

我想到了。我需要在 Startup.cs 中使用 MapType() 创建自定义模型

文件格式

public class Csv<T> : List<T> where T : IConvertible
{
    public Csv<T> Append(string delimitedValues)
    {
        var splitValues = delimitedValues
            .Split(',', StringSplitOptions.RemoveEmptyEntries)
            .Cast<string>();

        var convertedValues = splitValues
            .Select(str => Convert.ChangeType(str, typeof(T)))
            .Cast<T>();

        this.AddRange(convertedValues);

        return this;
    }

    public override string ToString()
    {
        return this.Aggregate("", (a,s) => $"{a},{s}").Trim(',');
    }
}
Run Code Online (Sandbox Code Playgroud)

启动文件

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddSwaggerGen(c =>
    {
        c.IncludeXmlComments(() => new XPathDocument(new FileStream(Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "MyApi.xml"), FileMode.Open)));
        c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1"});
        c.MapType<Csv<string>>(() => new Schema { Type = "string", Format = "string" });

    });
}
Run Code Online (Sandbox Code Playgroud)