自定义验证:从validationContext获取属性名称

tug*_*erk 5 .net asp.net asp.net-mvc asp.net-mvc-validation asp.net-mvc-3

对于我的 ASP.NET MVC 项目,我创建了一个自定义验证属性。这是我正在努力解决的代码:

  protected override ValidationResult IsValid(object value, ValidationContext validationContext) {

        //Here I need to resolve the url in order to make a call to that controller action and get the JSON result back

        var httpContext = new HttpContextWrapper(HttpContext.Current);
        var urlHelper = new UrlHelper(
            new System.Web.Routing.RequestContext(
                httpContext, new System.Web.Routing.RouteData()
            )
        );
        var url = urlHelper.Action(Action, Controller, null, 
            urlHelper.RequestContext.HttpContext.Request.Url.Scheme);

        var fullUrl = string.Format("{0}?{1}={2}", url, 
            /*validationContext.MemberName*/"term", value);

        if (!GetResult(fullUrl)) {

            var message = FormatErrorMessage(validationContext.DisplayName);
            return new ValidationResult(message);
        }

        return null;
    }
Run Code Online (Sandbox Code Playgroud)

您可以从下面的链接查看完整代码:

https://bitbucket.org/tugberk/tugberkug.mvc/src/6cc3d3d64721/TugberkUg.MVC/Validation/ServerSideRemoteAttribute.cs

对于fullUrl变量,我尝试将属性名称附加到查询字符串,但是当我使用 时validationContext.MemberName,我失败了。我通过将其静态化为“术语”来解决临时修复的问题,但这根本不是修复。

那么,从 中检索属性名称的方法是什么validationContext

Pet*_*arn 3

validationContext.DisplayName 可以解决问题吗?

然后您可以反映以获取 MemberName

var displayName = validationContext.DisplayName;

var memberName = validationContext.ObjectType.GetProperties()
    .Where(p => p.GetCustomAttributes(false).OfType<DisplayAttribute>().Any(a => a.Name == displayName))
    .Select(p => p.Name)
    .FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

可能吗?