[英]Data annotations attributes not working in asp net core
ASP Net core 2.2應用程序中,數據注釋屬性[必需]根本不起作用。 根據docs https://docs.microsoft.com/zh-CN/dotnet/api/system.componentmodel.dataannotations.requiredattribute?view=netframework-4.7.1#remarks 。 如果屬性為null,包含空字符串(“”)或僅包含空格字符,則會引發驗證異常。 但是,在我的應用程序中並非如此。
[HttpPost]
public IActionResult TranslateHtml(
[FromQuery] [Required] int value,
[FromForm] [Required(AllowEmptyStrings = false)]
string source)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
return Ok();
}
當我通過郵遞員發送請求並且不指定查詢字符串值和/或表單數據源ModelState.IsValid為true時。 我期望是錯誤的。
我找出了問題的根源。 我被包括了.AddMvcCore,並且默認情況下它根本不包括DataAnnotations。
services.AddMvcCore()
.AddDataAnnotations()
.AddCors()
.AddJsonFormatters()
我在Startup.cs中添加了.AddDataAnnotations,它的工作原理像一個超級按鈕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.