2

I have a method that have [FromBody] parameter but it ModelState.IsValid keep returning true if values are longer than they limited with MaxLength attributes in the mapped object.

public class AddUserMsg
{
    [MaxLength(10)]
    public string name;
}

[HttpPost("[action]")]
public IActionResult AddUser([FromBody] AddUserMsg msg)
{
    // Always true even if the name is longer than 10 symbols
    if (ModelState.IsValid)
    {
    }
}

I thought it suppose to validate posted data. Any ideas why it does not?

Ilya Chumakov
  • 23,161
  • 9
  • 86
  • 114
user1050035
  • 111
  • 2
  • 7

2 Answers2

4
public string name;

Property should be used instead of field.

public string Name { get; set };

ASP.NET 5, MVC6, WebAPI -> ModelState.IsValid always returns true

Community
  • 1
  • 1
Ilya Chumakov
  • 23,161
  • 9
  • 86
  • 114
1

You are looking for StringLengthAttribute. The StringLength is used for ViewModel validation. From docs:

The StringLength attribute lets you set the maximum length of a string property, and optionally its minimum length.

MaxLengthAttribute is used by Entity Framework to provide a hint to the dataprovider about the appropriate data type to use for a given property. As you can see from docs:

Entity Framework does not do any validation of maximum length before passing data to the provider. It is up to the provider or data store to validate if appropriate. For example, when targeting SQL Server, exceeding the maximum length will result in an exception as the data type of the underlying column will not allow excess data to be stored.

tmg
  • 19,895
  • 5
  • 72
  • 76
  • However, `MaxLength` is partly supported by MVC. http://stackoverflow.com/a/21696595/5112433 In OP case it would work for a property. – Ilya Chumakov May 20 '16 at 07:25