4

我正在使用 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; }
}

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

public object Post([FromBody]Client postedClient)

它通过 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)].

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

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

1 回答 1

6

之所以存在此验证,是因为对于引用类型的成员,每当反序列化该成员时,WebAPI 都可以检查该成员是否为空。对于值类型,没有空值,因此由格式化程序检查请求正文中是否存在该值。不幸的是,我们的 XML 格式化程序不支持 [Required] 属性,因此如果成员丢失,它不会引发模型状态错误。

如果您对某些格式化程序没有为缺少的值类型成员引发模型状态错误感到满意,则可以使用此行来删除验证:

config.Services.RemoveAll(typeof(ModelValidatorProvider), (provider) => provider is InvalidModelValidatorProvider);
于 2012-12-29T08:41:57.397 回答