webapi mvc4的必需注释对于整数属性失败,但适用于字符串

Nul*_*ead 5 jquery annotations asp.net-mvc-4 asp.net-web-api

当我进行ajax调用时,它会因500内部服务器错误而失败

Value-typed properties marked as [Required] must also be marked with [DataMember(IsRequired=true)]
Run Code Online (Sandbox Code Playgroud)

问题出在CallerID属性上.

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

[Required]
public int CallerID { get; set; }
Run Code Online (Sandbox Code Playgroud)

如果我将CallerID标记为字符串,则一切正常.
有什么想法吗?

Fil*_*p W 5

这是Web API中的一个已知问题,您可以在此处查看整个历史记录:http: //aspnetwebstack.codeplex.com/workitem/270

基本上,如果将[Required]应用于值类型(例如bool或int,string不是值类型),则会导致此错误.

你还需要考虑它 - 你正在创建int一个必需的属性 - 但作为一个值类型,它总是有值,值= 0,即使它没有被用户传递.也许你想的是int?相反?

您可以InvalidModelValidatorProvider完全删除(虽然可能不接受):

config.Services.RemoveAll(
typeof(System.Web.Http.Validation.ModelValidatorProvider), 
v => v is InvalidModelValidatorProvider);
Run Code Online (Sandbox Code Playgroud)

或者只是将DataContract应用于您的类:

[DataContract]
public class MyClass {

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

[DataMember(isRequired=true)]
public int CallerID { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

另一种解决方法是将int标记为可为空:

[Required]
public int? CallerID { get; set; }
Run Code Online (Sandbox Code Playgroud)