4 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個贊
雖然正確答案已經(jīng)提交,但我想提供一個例子。假設(shè)您已將 Swashbuckle.AspNetCore 包添加到您的項(xiàng)目中,并在 Startup.Configure(...) 中使用它,如下所示:
app.UseSwagger();
app.UseSwaggerUI(options =>
{
? ? options.SwaggerEndpoint("/swagger/v1/swagger.json", "My Web Service API V1");
? ? options.RoutePrefix = "api/docs";??
});
有一個像這樣的測試控制器操作端點(diǎn):
[HttpGet]? ? ? ??
public ActionResult GetAllItems()
{
? ? if ((new Random()).Next() % 2 == 0)
? ? {
? ? ? ? return Ok(new string[] { "value1", "value2" });
? ? }
? ? else
? ? {
? ? ? ? return Problem(detail: "No Items Found, Don't Try Again!");
? ? }
}
將產(chǎn)生如下所示的 swagger UI 卡/部分(運(yùn)行項(xiàng)目并導(dǎo)航到 /api/docs/index.html):
如您所見,沒有為端點(diǎn)提供“元數(shù)據(jù)”。
現(xiàn)在,將端點(diǎn)更新為:
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<string>), 200)]
[ProducesResponseType(404)]
public ActionResult GetAllItems()
{
? ? if ((new Random()).Next() % 2 == 0)
? ? {
? ? ? ? return Ok(new string[] { "value1", "value2" });
? ? }
? ? else
? ? {
? ? ? ? return Problem(detail: "No Items Found, Don't Try Again!");
? ? }
}
這根本不會改變端點(diǎn)的行為,但現(xiàn)在 swagger 頁面如下所示:
這好多了,因?yàn)楝F(xiàn)在客戶端可以看到可能的響應(yīng)狀態(tài)代碼是什么,以及對于每個響應(yīng)狀態(tài),返回數(shù)據(jù)的類型/結(jié)構(gòu)是什么。請注意,雖然我沒有定義 404 的返回類型,但 ASP.NET Core(我使用的是 .NET 5)足夠聰明,可以將返回類型設(shè)置為ProblemDetails。
如果這是您想要采取的路徑,最好將Web API 分析器添加到您的項(xiàng)目中,以接收一些有用的警告。
ps 我還想使用options.DisplayOperationId();?在 app.UseSwaggerUI(...) 配置中。通過這樣做,swagger UI 將顯示映射到每個端點(diǎn)的實(shí)際 .NET 方法的名稱。例如,上面的端點(diǎn)是對 /api/sample 的 GET,但實(shí)際的 .NET 方法稱為 GetAllItems()

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個贊
我認(rèn)為它對于不成功(200)返回代碼可以派上用場。假設(shè)如果其中一個失敗狀態(tài)代碼返回描述問題的模型,您可以指定該情況下的狀態(tài)代碼生成與成功情況不同的內(nèi)容。

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超1個贊
它用于為 API 探索/可視化工具(例如 Swagger (?https://swagger.io/?))生成開放 API 元數(shù)據(jù),以在文檔中指示控制器可能返回的內(nèi)容。

TA貢獻(xiàn)2003條經(jīng)驗(yàn) 獲得超2個贊
3種不同的使用選擇
在所有應(yīng)用程序控制器中:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
? ? ? ? app.UseSwaggerResponseCheck();
? //...
}
使用 ValidateStatusCodes 屬性的每個控制器操作:
[ApiController]
[Route("[controller]")]
public class ExampleController : ControllerBase
{
? ? [HttpGet]
? ? [ValidateStatusCodes] // <-- Use this
? ? [SwaggerOperation("LoginUser")]
? ? [SwaggerResponse(statusCode: StatusCodes.Status200OK, type: null, description: "signed user email account")]
? ? [SwaggerResponse(statusCode: StatusCodes.Status400BadRequest, type: null, description: "wrong email or password")]
? ? [Route("/users/login")]
? ? public virtual IActionResult LoginUser([FromQuery][Required()] string email, [FromQuery] string password)
? ? {
? ? ? ? ? ? if (email == "email@gmail.com")
? ? ? ? ? ? ? return Ok("success");
? ? ? ? ? ? else if (email == "")
? ? ? ? ? ? ? return BadRequest("email required");
? ? ? ? ? ? else
? ? ? ? ? ? ? return NotFound("user not found"); // 500 - InternalServerError because not attributed with SwaggerResponse.
? ? }
? ? // ...
? ? [HttpGet]
? ? [ValidateStatusCodes] // <-- Use this
? ? [ProducesResponseType(type: typeof(Account), StatusCodes.Status200OK)]
? ? [ProducesResponseType(StatusCodes.Status400BadRequest)]
? ? [Route("/users/login2")]
? ? public virtual IActionResult LoginUser2([FromQuery][Required()] string email, [FromQuery] string password)
? ? {
? ? ? ? ? ? if (email == "email@gmail.com")
? ? ? ? ? ? ? return Ok("success").Validate();
? ? ? ? ? ? else if (email == "")
? ? ? ? ? ? ? return BadRequest("email required").Validate();
? ? ? ? ? ? else
? ? ? ? ? ? ? return NotFound("user not found").Validate(); // Throws error in DEBUG or Development.
? ? }
}
使用 IStatusCodeActionResult.Validate() 的每個結(jié)果:
[ApiController]
[Route("[controller]")]
public class ExampleController : ControllerBase
{
? ? [HttpGet]
? ? [SwaggerOperation("LoginUser")]
? ? [SwaggerResponse(statusCode: StatusCodes.Status200OK, type: null, description: "signed user email account")]
? ? [SwaggerResponse(statusCode: StatusCodes.Status400BadRequest, type: null, description: "wrong email or password")]
? ? [Route("/users/login")]
? ? public virtual IActionResult LoginUser([FromQuery][Required()] string email, [FromQuery] string password)
? ? {
? ? ? ? ? ? if (email == "email@gmail.com")
? ? ? ? ? ? ? return Ok("success").Validate();
? ? ? ? ? ? else if (email == "")
? ? ? ? ? ? ? return BadRequest("email required").Validate();
? ? ? ? ? ? else if (email == "secret")
? ? ? ? ? ? ? return Unauthorized("hello");
? ? ? ? ? ? ? ? ?// Passed, independent of SwaggerResponse attribute.
? ? ? ? ? ? else
? ? ? ? ? ? ? return NotFound("user not found").Validate();
? ? ? ? ? ? ? ? ?// 500 - InternalServerError because not attributed with SwaggerResponse.
? ? }
? ? // ...
? ? [HttpGet]
? ? [ProducesResponseType(type: typeof(Account), StatusCodes.Status200OK)]
? ? [ProducesResponseType(StatusCodes.Status400BadRequest)]
? ? [Route("/users/login2")]
? ? public virtual IActionResult LoginUser2([FromQuery][Required()] string email, [FromQuery] string password)
? ? {
? ? ? ? ? ? if (email == "email@gmail.com")
? ? ? ? ? ? ? return Ok("success").Validate();
? ? ? ? ? ? else if (email == "")
? ? ? ? ? ? ? return BadRequest("email required").Validate();
? ? ? ? ? ? else
? ? ? ? ? ? ? return NotFound("user not found").Validate(); // Throws error in DEBUG or Development.
? ? }
}
- 4 回答
- 0 關(guān)注
- 525 瀏覽
添加回答
舉報