C# ValidationContext MemberName等于DisplayName
我创建了一个自定义验证属性,如下所示:C# ValidationContext MemberName等于DisplayName,c#,asp.net-web-api,C#,Asp.net Web Api,我创建了一个自定义验证属性,如下所示: [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class MandatoryAttribute : RequiredAttribute { public string DisplayName { get; private set; } protected override Validati
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class MandatoryAttribute : RequiredAttribute
{
public string DisplayName { get; private set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var memberName = validationContext.MemberName;
DisplayName = AttributeFunctions.GetDisplayName(validationContext);
return base.IsValid(value, validationContext);
}
public override string FormatErrorMessage(string name)
{
return AttributeFunctions.HasValidErrorMessageResource(this) ? base.FormatErrorMessage(DisplayName) : String.Format(Global.MandatoryValidationMessage, DisplayName);
}
}
public class Model
{
[Mandatory]
[Display(Name = "ResourceName", ResourceType = typeof(Resources.Global))]
public string SomeProperty { get; set; }
}
我的模型如下所示:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class MandatoryAttribute : RequiredAttribute
{
public string DisplayName { get; private set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var memberName = validationContext.MemberName;
DisplayName = AttributeFunctions.GetDisplayName(validationContext);
return base.IsValid(value, validationContext);
}
public override string FormatErrorMessage(string name)
{
return AttributeFunctions.HasValidErrorMessageResource(this) ? base.FormatErrorMessage(DisplayName) : String.Format(Global.MandatoryValidationMessage, DisplayName);
}
}
public class Model
{
[Mandatory]
[Display(Name = "ResourceName", ResourceType = typeof(Resources.Global))]
public string SomeProperty { get; set; }
}
由于某种原因,ValidationContext
的MemberName
将始终等于我在Display
属性中输入的任何内容。如果我对Display
属性进行注释,那么MemberName
就等于我所期望的“SomeProperty”
这是正常的行为吗?MemberName
不应该总是等于PropertyInfo.Name
属性吗
我之所以这样说,是因为我需要从验证上下文中检索属性info
,如果MemberName
没有给我正确的值,我就不能这样做。我也有同样的问题
这是webapi的一个bug,在mvc中可以正常工作
在webapi源代码中使用bug初始化
MVC5中的工人阶级
我将尝试覆盖此内容,如果有工作,我将更新此帖子。我也有同样的问题
这是webapi的一个bug,在mvc中可以正常工作
在webapi源代码中使用bug初始化
MVC5中的工人阶级
我将尝试覆盖这一点,如果工作,我会更新这篇文章