如果在將 Swagger-UI 文本框留空的情況下激活Version 0或Version 1按下,我會收到以下錯誤:Execute

在我看來,身體Get永遠不會被呼叫。對于其他版本,Get按預期呼叫。怎么會發生?
public class Contact
{
public string Name { get; set; } // Version 0
public string Name { get; set; } = null!; // Version 1
// public string Name { get; set; } = String.Empty; // Version 2
// public string? Name { get; set; } // Version 3
// public string? Name { get; set; } = String.Empty;// Version 4
public int Age { get; set; }
}
[ApiController]
[Route("api/[controller]/[action]")]
public class ContactsController : ControllerBase
{
[HttpGet]
public ActionResult Get([FromQuery] Contact c)
{
// The code below will never be executed when Version 1 is activated, why?
if (c.Name is null)
return Ok("Name is null");
if (c.Name == String.Empty)
return Ok("Name is empty");
return Ok("End reached");
}
}
uj5u.com熱心網友回復:
根據屬性的可空性以及我們在構造時設定的值,行為會有所不同。
這意味著:
ASP.NET Core 能夠識別屬性是標記為可空 ( string?) 還是不可空 ( string)。
ASP.NET Core 能夠呼叫或不呼叫控制器方法,具體取決于輸入。所以有代碼決定是否呼叫你的方法。
ASP.NET Core 能夠在呼叫控制器方法之前檢查屬性的值。
正如您在影像中的回應中看到的那樣,回應的一部分顯示The Name field is required. 這也導致我們:
ASP.NET Core 能夠知道Contact類屬性的名稱,這就是為什么回應特別告訴我們這Name是必需的。
版本 0 和版本 1 的共同部分是Name屬性
- 不可為空
- 具有
nullafter的值new Contact()
版本 2 和版本 4 的共同部分是Name屬性
- 具有
string.Emptyafter的值new Contact()
版本 3 和版本 4 的共同部分是Name屬性
- 可以為空
通過對上述行為的分析,我們可以推斷當驗證碼在不可為空的屬性中看到 null 時,它正在拒絕輸入。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/497165.html
