Guy
Guy

Reputation: 67340

How do you find the base url from a DLL in C#?

From within a DLL that's being called by a C#.NET web app, how do you find the base url of the web app?

Upvotes: 3

Views: 6922

Answers (5)

netadictos
netadictos

Reputation: 7722

As Alexander says, you can use HttpContext.Current.Request.Url but if you doesn't want to use the http://:

HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);

Upvotes: 1

Pablo
Pablo

Reputation: 36

If it's an assembly that might be referenced by non-web projects then you might want to avoid using the System.Web namespace.

I would use DannySmurf's method.

Upvotes: 1

Alexander Kojevnikov
Alexander Kojevnikov

Reputation: 17742

Will this work?

HttpContext.Current.Request.Url

UPDATE:

To get the base URL you can use:

HttpContext.Current.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)

Upvotes: 12

Guy
Guy

Reputation: 67340

I've come up with this although I'm not sure if it's the best solution:

string _baseUrl = String.Empty;
HttpContext httpContext = HttpContext.Current;
if (httpContext != null)
{
    _baseURL = "http://" + HttpContext.Current.Request.Url.Host;
    if (!HttpContext.Current.Request.Url.IsDefaultPort)
    {
        _baseURL += ":" + HttpContext.Current.Request.Url.Port;
    }
}

Upvotes: 0

TheSmurf
TheSmurf

Reputation: 15568

You can use Assembly.GetExecutingAssembly() to get the assembly object for the DLL.

Then, call Server.MapPath, passing in the FullPath of that Assembly to get the local, rooted path.

Upvotes: 0

Related Questions