需要验证datacontract和datamember

Joh*_*hn_ 4 .net c# asp.net-web-api

我正在使用web api构建一个API,当收到发布的值并将它们绑定到我的模型时,我得到的错误似乎不合适.

我有一个简单的模型如下:

public class Client
{
    [ScaffoldColumn(false)]
    [JsonIgnore]
    public int ClientID { get; set; }
    [Required, StringLength(75)]
    public string Name { get; set; }
    [Required]
    public bool Active { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

将此模型发送到我的控制器上的post方法时

public object Post([FromBody]Client postedClient)
Run Code Online (Sandbox Code Playgroud)

它通过x-www-form-urlencoded格式化程序,但它抛出:

Property 'Active' on type 'CreditSearch.Api.Models.Rest.Client' is invalid. Value-typed properties marked as [Required] must also be marked with [DataMember(IsRequired=true)] to be recognized as required. Consider attributing the declaring type with [DataContract] and the property with [DataMember(IsRequired=true)].
Run Code Online (Sandbox Code Playgroud)

我也试过它以json格式发送相同的数据,但我得到了相同的结果.我试图添加这些属性只是为了让代码工作,但Resharper和我自己找不到正确的引用.即便如此,我也不愿意在普通的MVC系统中验证之前不需要添加这些多余的属性.

  1. 我真的需要这些属性吗?以前不需要它们.
  2. 如果是这样,我需要添加哪些参考?

You*_*oui 6

这种验证的原因是因为对于引用类型的成员,每当成员被反序列化时,WebAPI都可以检查该成员是否为空.对于值类型,没有空值,因此由格式化程序检查该值是否存在于请求主体中.遗憾的是,我们的XML格式化程序不支持[Required]属性,因此如果缺少该成员,它不会引发模型状态错误.

如果某些格式化程序没有为缺少的值类型成员引发模型状态错误,那么可以使用此行删除验证:

config.Services.RemoveAll(typeof(ModelValidatorProvider), (provider) => provider is InvalidModelValidatorProvider);
Run Code Online (Sandbox Code Playgroud)