【问题标题】:Required variable Rest所需变量 Rest
【发布时间】:2018-10-22 10:47:41
【问题描述】:

我想使用 [POST] 发出请求,如果某个字段为空,我将不遵循服务。我想停止控制器中的流程。问题在于 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();

        }

想象一下正在发生的事情:

【问题讨论】:

  • 你能添加一个断点,并给我们看一个来自identityBrokerSettingsDetails的示例输出吗?
  • 我无法添加图片,但我可以描述:如果我使用 Tennant 而不是租户(租户是该程序正在等待)中的租户为 null,但 ModelState.IsValid 返回为 true .我不明白为什么
  • 添加图片链接(即Image of this happening: http://image.url.here),我可以把它转换成图片。
  • @FrankerZ 现在你可以看到图片了

标签: c# json rest


【解决方案1】:

对于字符串 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
}

【讨论】:

  • 这没有找到,因为我可以填充所有字段少一个,并且我的 IdentityBrokerSettingsDetails 创建了一个对象。我想检查一个是否为空或例如“” ModelState.IsInvalid 返回一个错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
  • 1970-01-01
  • 2019-03-22
  • 2014-09-03
  • 2011-07-28
  • 2011-06-10
相关资源
最近更新 更多