How do I find the absolute path of a controller action?

I need to create an action link and email the link. I would like to call something like this:

public string GetAbsolutePath(string actionName, string controllerName, string id)
{
    // Somehow generate the absolute path
}

      

I think I can use VirtualPathUtility.ToAbsolute (string virtualPath), but I'm not sure how to get the virtual path.

+2


source to share


4 answers


I ended up with this:



public static string AbsoluteAction(this UrlHelper url, string action, string controller, object routeValues)
{
    Uri requestUrl = url.RequestContext.HttpContext.Request.Url;

    string absoluteAction = string.Format("{0}://{1}{2}",
                                          requestUrl.Scheme,
                                          requestUrl.Authority,
                                          url.Action(action, controller, routeValues, null));
    return absoluteAction;
}

      

+1


source


You can use a routing engine to create a link for you. There are several ways to do this, for example. in the view you can link to the action with



<%= Url.Action(actionName, controllerName, new {id=id} %>

      

+1


source


Something like that:

public string GetAbsolutePath(string actionName, string controllerName, string id)
{
    var relUrl = Url.RouteUrl(new { controller = controllerName, action = actionName, id = id });

    return Request.Url.GetLeftPart(UriPartial.Authority).TrimEnd('/') + relUrl;
}

      

+1


source


You can use a routing engine to generate a route for you, given a controller and an action. Your controller's RouteCollection property can be used like this:

string virtualPath = 
    RouteCollection.GetVirtualPath(context, new { 
                                                  action = actionName, 
                                                  controller = controllerName, 
                                                  id = id
                                                }
                                  ).VirtualPath;

string url = VirtualPathUtility.ToAbsolute(virtualPath);

      

0


source







All Articles