Water Cooler v2
Water Cooler v2

Reputation: 33850

Get MVC application's absolute path like http://foo.com/bar/gar from a class library

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.

Upvotes: 0

Views: 166

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

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.

Upvotes: 2

Related Questions