-1

I want to do a request with [POST] and if some field it's null i don't follow to the Service. I want to stop the flow in the Controller. problem is with ModelState.IsValid it returns a true when it should be false and return a BadRequest

This is the code:

Model:

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;
        }
    }

Controller:

[HttpPost]
        public IActionResult PostIdentitySettingsDetails([FromBody] IdentityBrokerSettingsDetails identityBrokerSettingsDetails)
        {
            if (!ModelState.IsValid) //doesn't work
                return BadRequest();

        }

Image what is happening:

enter image description here

Blue
  • 22,608
  • 7
  • 62
  • 92
CMorillo
  • 191
  • 1
  • 10
  • 1
    Can you add a breakpoint, and show us a sample output from `identityBrokerSettingsDetails`? – Blue Oct 22 '18 at 10:51
  • i can't add picture, but I can describe: If I do a Post with Tennant and not tenant (tenant is that program is waiting) Tenant in IdentityBrokerSettingsDetails is null but ModelState.IsValid return is true. I don't understand why – CMorillo Oct 22 '18 at 10:57
  • Add the picture link (ie. `Image of this happening: http://image.url.here`), and I can convert it to an image. – Blue Oct 22 '18 at 10:57
  • @FrankerZ now you can see the image – CMorillo Oct 22 '18 at 11:02
  • Possible duplicate of [ModelState.IsValid even when it should not be?](https://stackoverflow.com/questions/17923622/modelstate-isvalid-even-when-it-should-not-be) – Blue Oct 22 '18 at 11:07
  • Maybe this solution will help you: https://stackoverflow.com/a/23939901/8300328 – DerStarkeBaer Oct 22 '18 at 11:20

1 Answers1

0

For the string Tenant, you can use the following: [DisplayFormat(ConvertEmptyStringToNull=false)]

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

Also, you can check

if (identityBrokerSettingsDetails == null || !Model.IsValid)
{ // Bad request code here
}
Gauravsa
  • 6,330
  • 2
  • 21
  • 30
  • This not found because i can fill all fields less one and my IdentityBrokerSettingsDetails create a object. I want check if one is null or for example "" ModelState.IsInvalid return a false – CMorillo Oct 22 '18 at 12:03