当我向我的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
属性永远不会调用该方法,甚至可能不会自己调用。
我是否错误地使用了标签?它为什么从未被称为?
答案 0 :(得分:1)
我知道这个问题已经很老了,但是Swagger示例不支持GET请求参数(查询参数)。仅当参数在请求正文中(例如POST请求)时才有效