views:

2012

answers:

5

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?

A: 

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.

DannySmurf
I'm looking for the URL of the site not the directory path. Thanks!
Guy
+6  A: 

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)
Alexander Kojevnikov
Thanks Alexander - I worked out something using that part of HttpContext.
Guy
A: 

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;
    }
}
Guy
Check my updated answer for an alternative solution.
Alexander Kojevnikov
A: 

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.

Pablo
A: 

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);
netadictos