0

From within an external class library, I'd like to convert a path like so:

~/bar/gar

to a path like so:

http://foo.com/bar/gar

This is an ASP.NET MVC application.

Since we're not in a view, I cannot use the UrlHelper class from within my external class library. That's because that class is an instance class and it does not have a default, parameterless constructor. It needs an instance of System.Web.Routing.RequestContext.

Another option I tried was:

var absoluteRedirectUri = System.Web.VirtualPathUtility
                     .ToAbsolute(settings.Parameters.RedirectUri.Value, 
                     HttpContext.Current.Request.ApplicationPath);

But that still yields /bar/gar instead of http://foo.com/bar/gar.

Water Cooler v2
  • 32,724
  • 54
  • 166
  • 336
  • Does this help - http://stackoverflow.com/questions/12239006/how-do-i-resolve-a-path-relative-to-an-asp-net-mvc-4-application-root – Dean.DePue Jun 04 '14 at 11:00
  • No. That's not my question. `Server.MapPath` yields the path of the file on the hard drive of the server. I am after completing a simple content path with the domain name. Apples and oranges. – Water Cooler v2 Jun 04 '14 at 11:02

1 Answers1

2

You can do something like this:

public string FullyQualifiedApplicationPath
{
  get
  {
    //Return variable declaration
    string appPath = null;

    //Getting the current context of HTTP request
    HttpContext context = HttpContext.Current;

    //Checking the current context content
    if (context != null)
    {
      //Formatting the fully qualified website url/name
      appPath = string.Format("{0}://{1}{2}{3}",
        context.Request.Url.Scheme,
        context.Request.Url.Host,
        context.Request.Url.Port == 80
          ? string.Empty : ":" + context.Request.Url.Port,
        context.Request.ApplicationPath);
    }
    if (!appPath.EndsWith("/"))
      appPath += "/";
    return appPath;
  }
}

Here is the link where you can read in detail.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160