Mvc icon indicating copy to clipboard operation
Mvc copied to clipboard

FromRoute property empty but ModelState valid?

Open erwinwildenburg opened this issue 9 years ago • 3 comments

Hi,

I have the following object:

    public class ModuleRequest : Request
    {
        [Required]
        [FromRoute]
        public string ModuleName { get; set; }

        [Required]
        [FromRoute]
        public string ModuleVersion { get; set; }
    }

And when I call the Action with the following url, it says the ModelState is valid: Modules(ModuleName='',ModuleVersion='')/ModuleContent");

I would expect it would fail as the properties are not filled with a value. I tried adding BindRequired but it doesn't help eighter sadly...

It it something I am doing wrong?

erwinwildenburg avatar Feb 05 '17 16:02 erwinwildenburg

The validation attributes specify behavior that you want to enforce on the model properties they are applied to. The Required and MinimumLength attributes indicates that a property must have a value; but nothing prevents a user from entering white space to satisfy this validation. The RegularExpression attribute is used to limit what characters can be input.

According to this documentation: Adding validation rules to the movie model

Since you are having blank values applied to the model, it is not failing validation. I would use the RegularExpression attribute to not allow white space.

[RegularExpression(@"^\S*$")]

Huntk23 avatar Feb 07 '17 22:02 Huntk23

@erwinwildenburg have you debugged and confirmed the expected action is executed for this URL? What are the signature of and route template for that action? Are non-empty values correctly bound to the action parameters?

@Huntk23 the [Required] documentation states

A validation exception is raised if the property is null, contains an empty string (""), or contains only white-space characters.

Put another way, the AllowEmptyStrings property defaults to false.

dougbu avatar Feb 11 '17 22:02 dougbu

@dougbu You are right... The action didn't get called it just returned not found since it didn't match the route. I would expect the action would be called, but the ModelState to be invalid.

Thanks for your help!

erwinwildenburg avatar Feb 13 '17 11:02 erwinwildenburg