所需变量休息

时间:2018-10-22 10:47:42

标签: c# json rest

我想用[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();

        }

了解正在发生的事情:

enter image description here

1 个答案:

答案 0 :(得分:0)

对于字符串Tenant,可以使用以下命令:  [DisplayFormat(ConvertEmptyStringToNull=false)]

https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.parameter.convertemptystringtonull?redirectedfrom=MSDN&view=netframework-4.7.2

还可以检查

if (identityBrokerSettingsDetails == null || !Model.IsValid)
{ // Bad request code here
}