从服务器端的Route Values解析URL

tug*_*erk 4 .net c# asp.net asp.net-mvc asp.net-mvc-validation

我正在尝试创建一个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);
    }
}
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

Dar*_*rov 7

var httpContext = new HttpContextWrapper(HttpContext.Current);
var urlHelper = new UrlHelper(new RequestContext(httpContext, new RouteData()));
var url = urlHelper.Action(Action, Controller, RouteValues);
Run Code Online (Sandbox Code Playgroud)

  • @tugberk,不,它不会解析为完整的网址.如果你想要一个绝对的url,你将不得不使用适当的重载:`var url = urlHelper.Action(Action,Controller,RouteValues,urlHelper.RequestContext.HttpContext.Request.Url.Scheme);` (2认同)