【发布时间】:2017-10-22 14:12:41
【问题描述】:
当我向我的 API 添加 swagger 时,我想获取默认值和响应示例。我添加了 NuGet 包并尝试关注this tutorial。 SwaggerResponseExample 属性可以正常工作,但 SwaggerRequestExample 似乎只是被忽略了。
我的动作定义如下
[SwaggerRequestExample(typeof(int), typeof(PersonExamples.Request))]
[SwaggerResponseExample(200, typeof(PersonExamples.Response))]
/* more attribute & stuff */
public IActionResult Get(int id) { /* blabla */ }
PersonExamples 类定义如下(不相关的代码已删除)
public class PersonExamples
{
public class Request : IExamplesProvider
{
public object GetExamples() { return _persons.List().First().Id; }
}
public class Response : IExamplesProvider
{
public object GetExamples() { return _persons.List().First(); }
}
}
这里也是Startup.cs的相关部分
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(conf =>
{
conf.SwaggerDoc(_documentationPrefix, new Info
{
Title = "Global",
Version = "v0",
});
conf.OperationFilter<ExamplesOperationFilter>();
var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "Global.xml");
conf.IncludeXmlComments(filePath);
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSwagger(opt =>
{
opt.RouteTemplate = "{documentName}/swagger.json";
});
if (env.IsDevelopment())
{
app.UseSwaggerUI(conf =>
{
conf.SwaggerEndpoint($"/{_documentationPrefix}/swagger.json", "DataService API");
conf.RoutePrefix = "doc/swagger";
});
}
}
当我运行我的项目并转到 swagger.json 页面时,我注意到响应示例编写正确,但找不到请求示例。进一步调试后,我注意到在调用页面时会命中位于PersonExamples.Response.GetExamples 中的断点,但位于PersonExamples.Request.GetExamples 方法中的断点不会。所以我相信SwaggerRequestExample 属性永远不会调用该方法,甚至可能不会被自己调用。
我是否不当使用了标签?为什么它从来没有被调用?
【问题讨论】:
-
您是在使用 NuGet 包,还是尝试手动实现代码?如果您不使用 NuGet 包,我建议您先尝试一下,因为示例代码中可能存在一个细微的错误,而实际发布的代码中不一定存在。
-
我正在使用 NuGet 包。
标签: c# swagger asp.net-core-2.0 swashbuckle