问题描述
我有一个包含以下端点的 ASP.NET Core Web API.
I have an ASP.NET Core Web API that contains the following endpoint.
[HttpGet]
[Route("models/{ids}")]
[Produces(typeof(IEnumerable<Model>))]
public IActionResult Get
(
[ModelBinder(typeof(CsvModelBinder<string>))] IEnumerable<string> ids
)
{
// Get models
return Ok(models);
}
此端点采用 CSV 的 Id 列表(例如 /models/a,b,c
)并返回相应 Model
对象的 JSON 数组.CsvModelBinder
是我编写的 IModelBinder
的自定义实现,它将 Id 的 CSV 列表拆分为我可以使用的 IEnumerable
在我的查询中查找对象.这一切都很好.
This endpoint takes a CSV list of Ids (e.g. /models/a,b,c
) and returns a JSON array of the corresponding Model
objects. CsvModelBinder<string>
is a custom implementation of IModelBinder
I wrote that splits the CSV list of Ids into an IEnumerable<string>
that I can use in my query to go find the objects. This all works great.
我现在要做的是使用 NSwag 生成客户端库,但这被证明是有问题的,因为 Swashbuckle 正在生成将 ids
参数描述为 IEnumerable<string> 的 Swagger.
,而不是 字符串
.
What I'm now trying to do is generate a client library using NSwag, but this is proving problematic because Swashbuckle is generating Swagger that describes the ids
parameter as an IEnumerable<string>
, not a string
.
选项 A: 有没有办法告诉 Swashbuckle 将参数描述为 string
而不是 IEnumerable
?
Option A: Is there a way to tell Swashbuckle to describe the parameter as a string
instead of as an IEnumerable<string>
?
选项 B: 有没有办法告诉 NSwag 在生成请求 URL 时应该将这个 IEnumerable
参数编组为 CSV?
Option B: Is there a way to tell NSwag that this IEnumerable<string>
parameter should be marshalled into a CSV when generating the request URL?
推荐答案
我想通了.我需要在 Startup.cs 中使用 MapType() 创建一个自定义模型
I figured it out. I needed to create a custom model use MapType() in Startup.cs
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(',');
}
}
Startup.cs
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" });
});
}
这篇关于如何将自定义模型绑定器与 Swashbuckle、Swagger 和 NSwag 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!