当我向 API 添加 swagger 时,我想要获取默认值和响应示例。我添加了 NuGet 包并尝试遵循本教程 https://mattfrear.com/2016/01/25/generating-swagger-example-requests-with-swashbuckle/. The SwaggerResponseExample
属性工作正常,但SwaggerRequestExample
似乎只是被忽略了。
我的行动定义如下
[SwaggerRequestExample(typeof(int), typeof(PersonExamples.Request))]
[SwaggerResponseExample(200, typeof(PersonExamples.Response))]
/* more attribute & stuff */
public IActionResult Get(int id) { /* blabla */ }
The 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
属性从不调用该方法,甚至可能不会调用其本身。
我是否不当使用了标签?为什么它从来没有被调用过?