views:

2748

answers:

5

Hi,

I am wondering what the best way to obtain the current domain is in ASP.NET?

For instance:

http://www.domainname.com/subdir/ should yield http://www.domainname.com http://www.sub.domainname.com/subdir/ should yield http://sub.domainname.com

As a guide, I should be able to add a url like "/Folder/Content/filename.html" (say as generated by Url.RouteUrl() in ASP.NET MVC) straight onto the URL and it should work.

+17  A: 

As per this link a good starting point is:

Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host

However, if the domain is http://www.domainname.com:500 this will fail.

The following resolves this:

Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.Port != 80 ? ":" + Request.Url.Port : "")

However, I get the feeling that assuming port 80 may be browser or even user configuration dependant.

Graphain
Why assume port 80 here? If you remove that assumption, the code looks like a catch-all. When you assume port 80, you will fail in many scenarios (see comments on other anwers). If you want to remove the port number if possible, you must check that the port number is the default for the scheme in question, and that the scheme supports default port numbers.
bzlm
Yeah see the note that port 80 may be a bad idea. I don't know any other way around this though which is why I mentioned it will need to be configuration dependant.
Graphain
A: 

How about:

String domain = "http://" + Request.Url.Host
jwalkerjr
Not bad, but what if your site has secure pages i.e. https://What if your domain is not hosted on port 80?
Graphain
A: 

How about:

NameValueCollection variables = HttpContext.Current.Request.ServerVariables; string protocol = (variables["SERVER _ PORT _ SECURE"] == "1") ? "https://" : "http://"; string domain = variables["SERVER _ NAME"]; string port = variables["SERVER _ PORT"];

(Remove the spaces around the underscores in the server variable indexers.)

Derek Lawless
A: 

Another way:


string domain;
Uri url = HttpContext.Current.Request.Url;
domain= url.AbsoluteUri.Replace(url.PathAndQuery, string.Empty);
+3  A: 

Same answer as Graphain's but with some modification. This checks for the default port instead.

Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host +
(Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port)
Carlos Muñoz