c# - SwashBuckle Swagger-UI 对具有 FromQuery 属性的 HTTP GET 方法的示例请求
问题描述
我已经设法使用POST 方法向我SwashBuckle.AspNetCore
的Web API 添加示例:Swashbuckle.AspNetCore.Filters
DTO
public class ExampleDTO
{
public string MyFoo { get; set; }
}
示例请求
public class ExampleDTOExample : IExamplesProvider<ExampleDTO>
{
public ExampleDTO GetExamples()
{
return new ExampleDTO()
{
MyFoo = "bar"
};
}
}
控制器方法
[SwaggerOperation(
Summary = "...",
Description = "...",
OperationId = "PostFoo"
)]
[SwaggerResponse(200, "Returns ...", typeof(int))]
[HttpPost]
[Route("post-foo")]
public ActionResult<int> PostFoo([FromBody]ExampleDTO request)
{
throw new NotImplementedException();
}
这项工作非常好。当我单击“试用”按钮时,我将“bar”作为属性 foo 的预填充值。
但是,当我尝试对 GET 请求执行相同操作时,例如,使用来自这样的查询的参数时,文本框不会预填充值“bar”:
public class ExampleDTO
{
[FromQuery(Name = "foo")]
public string MyFoo { get; set; }
}
控制器方法
[SwaggerOperation(
Summary = "...",
Description = "...",
OperationId = "GetFoo"
)]
[SwaggerResponse(200, "Returns ...", typeof(int))]
[HttpGet]
[Route("get-foo")]
public ActionResult<int> GetFoo([FromQuery]ExampleDTO request)
{
throw new NotImplementedException();
}
如何强制文本框预填充示例值?到目前为止,我已经找到了一个解决方案来指定我不想要的默认值。我只想在 Swagger UI 中使用属性作为默认值。
解决方案
这不是示例,而是默认值。
这是我过去做过的事情:
"/attrib/{payId}": {
"get": {
"tags": [
"Attribute"
],
"operationId": "Attribute_Get",
"consumes": [],
"produces": [
"application/json",
"text/json",
"text/html"
],
"parameters": [
{
"name": "payId",
"in": "path",
"required": true,
"type": "integer",
"format": "int32",
"default": 123
}
]
http://swagger-net-test.azurewebsites.net/swagger/ui/index?filter=Attribute#/Attribute/Attribute_Get
这是另一种同时具有默认值和示例的情况
"Company": {
"required": [
"Id",
"MyId"
],
"properties": {
"Id": {
"description": "The Unique Company ID",
"example": "123",
"type": "integer",
"format": "int32",
"default": 456
},
"MyId": {
"example": 123,
"type": "integer",
"format": "int32"
},
http://swagger-net-test.azurewebsites.net/swagger/ui/index#/Company/Company_Get2
您可以看到示例不是 Swagger UI 中显示的示例