我想用[POST]发出请求,如果某个字段为空,则我不关注服务。我想停止Controller中的流程。问题出在ModelState.IsValid上,当它为false时返回true并返回BadRequest
这是代码:
型号:
public class IdentityBrokerSettingsDetails
{
[Required(AllowEmptyStrings = false)]
public string Tenant { get; set; }
// With interrogation mark you make it nullable
[Required]
public bool? Account { get; set; }
[Required]
public bool? StatusUserLogin { get; set; }
public IdentityBrokerSettingsDetails(string tenant, bool? account, bool? statusUserLogin)
{
Tenant = tenant;
Account = account;
StatusUserLogin = statusUserLogin;
}
}
控制器:
[HttpPost]
public IActionResult PostIdentitySettingsDetails([FromBody] IdentityBrokerSettingsDetails identityBrokerSettingsDetails)
{
if (!ModelState.IsValid) //doesn't work
return BadRequest();
}
了解正在发生的事情:
答案 0 :(得分:0)
对于字符串Tenant,可以使用以下命令:
[DisplayFormat(ConvertEmptyStringToNull=false)]
还可以检查
if (identityBrokerSettingsDetails == null || !Model.IsValid)
{ // Bad request code here
}