Model validation - Why ModelState.IsValid always returns true even when no values are supplied?

点点圈 提交于 2020-01-03 06:19:09

问题


This is regarding WEBAPI and the following is my Model class.

    public class Request
    {
        public int Id { get; set; }
        public string Name { get; set; }
        [Required]
        public Gender Gender { get; set; }
    }

And my controller function (POST)

public class Values1Controller : ApiController
    {
        public IHttpActionResult Post([FromBody] Models.Request request)
        {
            if (!ModelState.IsValid)
            {
               return BadRequest();
            }
            var gender = request.Gender;
            var id = request.Id;
            var name = request.Name;
            // do some operations!
            return Ok();
        }
    }

And the xml that I submit along with each request.

<Request xmlns:i="http://www.w3.org/2001/XMLSchema-instance" 
                xmlns="http://schemas.datacontract.org/2004/07/webapi1.Models">
  <id>1</id>
  <name>testName</name>      
</Request>

In the above XML post data, I do not supply a value for Gender at all, which are marked as [required].

But the ModelState.IsValid returns true, even when in the above XML there is no value supplied for Gender.

How to prevent WebAPI from assigning default values to a enum in the model ?

Any ideas Why ?


回答1:


I don't know why your model is valid if you don't supply gender, but you can make this value not have a default value by defining the Gender value as nullable, as follows:

public class Request
{
    public int id { get; set; }

    public string Name { get; set; }

    [Required]
    public Gender? Gender { get; set; }
}

Alternatively you can specify a default value for gender, as follows:

public enum Gender
{
    Unknown = 0,
    Male,
    Female
} 

Update I now can see the difference between our results, again using Postman, if I submit a raw request as xml:

Header: Content-Type text/xml

<Request xmlns:i="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns="http://schemas.datacontract.org/2004/07/webapi1.Models">
    <id>1</id>
    <Name>testName</Name>      
</Request>

My model is valid, however if I submit x-www-form-urlencoded data:

Header: Content-Type application/x-www-form-urlencoded

id=1,Name=testname

Then my model is invalid, even though the value type has a value, my modelstate tells me that the Gender property is required.

As x-www-form-urlencoded is part of the query string then I guess that MVC is able to determine that the value was missing, but when the data is submitted as plain xml it can't determine this.

I suggest that if you want the required attribute to work in all cases, you make your value types nullable as follows:

[Required]
public Gender? Gender { get; set; }



回答2:


You just put the Required validate, but you didn't check the value like this:

[RegularExpression("^[0-9]*$", ErrorMessage = "Your fill the wrong content!")]

and if you want to set the default value before save, you can do something like this in your class:

public Request()
    {
        Gender = "male";
        Name = "default name"
    }

Hope to help!



来源:https://stackoverflow.com/questions/24240834/model-validation-why-modelstate-isvalid-always-returns-true-even-when-no-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!