Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required annotation for webapi mvc4 fails for an integer property but works for string

When I make an ajax call, it fails with 500 Internal server error

Value-typed properties marked as [Required] must also be marked with [DataMember(IsRequired=true)]

The problem is with CallerID property.

[Required]
public string AccountTypeID { get; set; }

[Required]
public int CallerID { get; set; }

If I mark CallerID as string, everything works well.
Any ideas why?

like image 672
Null Head Avatar asked Jan 08 '13 23:01

Null Head


1 Answers

This is a known issue in Web API, you can see the whole history here: http://aspnetwebstack.codeplex.com/workitem/270

Basically, if you apply [Required] to a value type (such as bool or int, string is not a value type) it will cause this error.

Also you need to think about it - you are making int a required property - but as a value type it will always have value, value=0 even if it's not passed by the user. Perhaps you were thinking of int? instead?

You can either remove the InvalidModelValidatorProvider altogether (which may not be acceptable though):

config.Services.RemoveAll(
typeof(System.Web.Http.Validation.ModelValidatorProvider), 
v => v is InvalidModelValidatorProvider);

Or just apply DataContract to your class:

[DataContract]
public class MyClass {

[DataMember(isRequired=true)]
public string AccountTypeID { get; set; }

[DataMember(isRequired=true)]
public int CallerID { get; set; }
}

One other workaround, mark the int as nullable:

[Required]
public int? CallerID { get; set; }
like image 111
Filip W Avatar answered Sep 25 '22 05:09

Filip W