4

我正在尝试创建一个 ValidationAttribute (用于仅在服务器端有效的远程验证),并且在 IsValid 方法中,我需要从 url 路由值解析 url。这是我的初始设置:

public class ServerSideRemoteAttribute : ValidationAttribute {

    public string Controller { get; set; }
    public string Action { get; set; }
    public object RouteValues { get; set; }

    public ServerSideRemoteAttribute(string controller, string action) {

        this.Controller = controller;
        this.Action = action;
    }

    public ServerSideRemoteAttribute(string controller, string action, object routeValues) {

        this.Controller = controller;
        this.Action = action;
        this.RouteValues = routeValues;
    }

    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

        return base.IsValid(value, validationContext);
    }
}

有什么想法吗?

4

1 回答 1

7
var httpContext = new HttpContextWrapper(HttpContext.Current);
var urlHelper = new UrlHelper(new RequestContext(httpContext, new RouteData()));
var url = urlHelper.Action(Action, Controller, RouteValues);
于 2011-11-06T10:32:46.317 回答