亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Net Core API:ProducesResponseType 的用途

Net Core API:ProducesResponseType 的用途

C#
慕村225694 2023-09-24 15:56:08
我想了解的目的ProducesResponseType.微軟定義為a filter that specifies the type of the value and status code returned by the action.所以我很好奇如果一個人不放置ProductResponseType?系統如何處于不利地位,或者是否會產生負面后果?Microsoft API 不是已經自動固有地知道返回的狀態代碼的類型/值嗎?[ProducesResponseType(typeof(DepartmentDto), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)]來自 Microsoft 的文檔:ProducesResponseTypeAttribute 類
查看完整描述

4 回答

?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

雖然正確答案已經提交,但我想提供一個例子。假設您已將 Swashbuckle.AspNetCore 包添加到您的項目中,并在 Startup.Configure(...) 中使用它,如下所示:


app.UseSwagger();

app.UseSwaggerUI(options =>

{

? ? options.SwaggerEndpoint("/swagger/v1/swagger.json", "My Web Service API V1");

? ? options.RoutePrefix = "api/docs";??


});

有一個像這樣的測試控制器操作端點:


[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!");

? ? }

}

將產生如下所示的 swagger UI 卡/部分(運行項目并導航到 /api/docs/index.html):

https://img1.sycdn.imooc.com/650febd1000179d814300421.jpg

如您所見,沒有為端點提供“元數據”。


現在,將端點更新為:


[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!");

? ? }

}

這根本不會改變端點的行為,但現在 swagger 頁面如下所示:

https://img1.sycdn.imooc.com/650febe10001e2e214330863.jpg

這好多了,因為現在客戶端可以看到可能的響應狀態代碼是什么,以及對于每個響應狀態,返回數據的類型/結構是什么。請注意,雖然我沒有定義 404 的返回類型,但 ASP.NET Core(我使用的是 .NET 5)足夠聰明,可以將返回類型設置為ProblemDetails。

如果這是您想要采取的路徑,最好將Web API 分析器添加到您的項目中,以接收一些有用的警告。

ps 我還想使用options.DisplayOperationId();?在 app.UseSwaggerUI(...) 配置中。通過這樣做,swagger UI 將顯示映射到每個端點的實際 .NET 方法的名稱。例如,上面的端點是對 /api/sample 的 GET,但實際的 .NET 方法稱為 GetAllItems()


查看完整回答
反對 回復 2023-09-24
?
蝴蝶不菲

TA貢獻1810條經驗 獲得超4個贊

我認為它對于不成功(200)返回代碼可以派上用場。假設如果其中一個失敗狀態代碼返回描述問題的模型,您可以指定該情況下的狀態代碼生成與成功情況不同的內容。

查看完整回答
反對 回復 2023-09-24
?
冉冉說

TA貢獻1877條經驗 獲得超1個贊

它用于為 API 探索/可視化工具(例如 Swagger (?https://swagger.io/?))生成開放 API 元數據,以在文檔中指示控制器可能返回的內容。



查看完整回答
反對 回復 2023-09-24
?
湖上湖

TA貢獻2003條經驗 獲得超2個贊

3種不同的使用選擇

在所有應用程序控制器中:

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 protected]")

? ? ? ? ? ? ? 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 protected]")

? ? ? ? ? ? ? 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() 的每個結果:

[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 protected]")

? ? ? ? ? ? ? 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 protected]")

? ? ? ? ? ? ? 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.

? ? }

}


查看完整回答
反對 回復 2023-09-24
  • 4 回答
  • 0 關注
  • 535 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號