Mor*_*idt 3 c# swagger swashbuckle asp.net-core
我的应用程序是ASP.NET Core 1.0 Web API。
我有以下控制器:
[HttpGet("{someData:MinLength(5):MaxLength(5)}")]
[Produces("application/json")]
public async Task<IActionResult> GetSomeData(string someData)
{
return this.Ok(JsonConvert.SerializeObject("Data is: " + someData));
}
Run Code Online (Sandbox Code Playgroud)
例如,每当我传递字符串“ 111”时,sagger就会向我显示以下消息:
我如何获得一个响应机构,例如:
“请输入5个数字”
谢谢
您可以使用注释操作,[ProducesResponseType(typeof(ModelStateDictionary), (int)HttpStatusCode.OK)]以返回典型的Dictionary类型的错误消息,例如使用时return BadRequest(ModelState)。
但是您不能在模式定义中返回文本。它用于json结构,而不用于错误消息。相反,您应该使用xmldoc(并在swagger中启用它)向参数添加描述。
/// <summary>
/// Returns some data based on <paramref name="someData"/> parameter.
/// </summary>
/// <param name="someData">Some data. (Must be exactly 5 characters wide)</param>
/// <response code="200">Returns indexed tags on success</response>
/// <response code="400">Invalid data sent</response>
/// <returns>A paged list of results</returns>
[HttpGet("{someData:MinLength(5):MaxLength(5)}")]
[ProducesResponseType(typeof(MyReturnType), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(void), (int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetSomeData(string someData)
{
}
Run Code Online (Sandbox Code Playgroud)
另外,您还需要在项目的属性中启用xmldocs的构建。
并添加到您的启动中:
services.AddSwaggerGen(options =>
{
...
var appEnv = PlatformServices.Default.Application;
options.IncludeXmlComments(Path.Combine(appEnv.ApplicationBasePath, $"{appEnv.ApplicationName}.xml"));
...
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2104 次 |
| 最近记录: |