需要验证数据合同和数据成员 [英] Validation datacontract and datamember required

查看:74
本文介绍了需要验证数据合同和数据成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用网络API来构建API,并且在接收到发布的值并将其绑定到我的模型时,我得到了一个错误,该错误似乎不合时宜。

I'm using the web api to build an API and when receiving the posted values and binding them to my model I get an error that seems out of place.

我的模型很简单,如下所示:

I have a simple model exactly as below:

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方法中

When sending this model through into my post method on my controller

public object Post([FromBody]Client postedClient)

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

it goes through the x-www-form-urlencoded formatter but it throws:

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系统中进行验证之前并不需要的多余属性。

I also tried it send the same data in json format but I get the same result. I tried to add these attributes just to get the code working but Resharper and myself cannot find the correct reference. Even so I'd prefer not to add this superfluousness attributes that haven't been required before when validating in a plain MVC system.


  1. 我真的需要这些属性吗?

  2. 如果是的话,我需要添加哪些引用?


推荐答案

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

The reason this validation is there is because for reference-typed members, whenever the member is deserialized WebAPI can check that the member is not null. For value types, there is no null value so it's up to the formatter to check that the value is present in the request body. Unfortunately, our XML formatter doesn't support the [Required] attribute so it won't raise a model state error if the member is missing.

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

If you're OK with certain formatters not raising model state errors for the missing value-typed members, you can use this line to remove the validation:

config.Services.RemoveAll(typeof(ModelValidatorProvider), (provider) => provider is InvalidModelValidatorProvider);

这篇关于需要验证数据合同和数据成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆