Web API可空必需属性需要DataMember属性

jor*_*hmv 21 asp.net-mvc data-annotations asp.net-web-api

我在Web API Post操作上收到以下VM

public class ViewModel
{
    public string Name { get; set; }

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

当我发帖时,我收到以下错误:

"ViewModel"类型的媒体"街道"无效.标记为[必需]的值类型属性也必须标记为[DataMember(IsRequired = true)],以便根据需要进行识别.考虑使用[DataContract]归因声明类型,使用[DataMember(IsRequired = true)]归因属性.

似乎错误是明确的,所以我只想完全确定当你有一个具有必需的可空属性的类时,需要使用[DataContract]和[DataMember]属性.

有没有办法避免在Web API中使用这些属性?

akn*_*ds1 20

我和你一样面临着同样的问题,我认为这完全是胡说八道.使用值类型,我可以看到它[Required]不起作用,因为值类型属性不能为null,但是当你有一个可以为空的值类型时,应该没有任何问题.但是,Web API模型验证逻辑似乎以相同的方式处理非可空和可空值的类型,因此您必须解决它.我在Web API论坛中找到了解决方法并且可以确认它是否有效:创建一个ValidationAttribute子类并应用它而不是RequiredAttribute在可空的值类型属性上:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

public class NullableRequiredAttribute : ValidationAttribute, IClientValidatable
{
    public bool AllowEmptyStrings { get; set; }

    public NullableRequiredAttribute()
        : base("The {0} field is required.")
    {
        AllowEmptyStrings = false;
    }

    public override bool IsValid(object value)
    {
        if (value == null)
            return false;

        if (value is string && !this.AllowEmptyStrings)
        {
            return !string.IsNullOrWhiteSpace(value as string);
        }

        return true;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var modelClientValidationRule = new ModelClientValidationRequiredRule(FormatErrorMessage(metadata.DisplayName));
        yield return modelClientValidationRule;
    }
}
Run Code Online (Sandbox Code Playgroud)

NullableRequiredAttribute正在使用中:

public class Model
{
    [NullableRequired]
    public int? Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

  • @jorgehmv我认为这是一个错误,直到有人说服我. (3认同)