views:

107

answers:

4

I need to generate a link to an action and send the link by email. I'd 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 either.

+1  A: 

You can use the routing mechanism to generate the link for you. There are several ways to do this, e.g. in the view you can generate a link to an action with

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

Something like this:

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;
}
eu-ge-ne
A: 

You can use the routing engine to generate the route for you given the controller and action. The RouteCollection property of your controller can be used as following:

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

string url = VirtualPathUtility.ToAbsolute(virtualPath);
womp
A: 

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;
}
Mike Comstock