Retrieve domain url
23,877
Solution 1
you should do some string manipulation on this answer :
how to get url of the current page in c#
in addition take a look at segments.
Solution 2
You have many options:
string root = this.ResolveUrl("~")
Or
Uri requestUri = Context.Request.Url;
string baseUrl = requestUri.Scheme + Uri.SchemeDelimiter + requestUri.Host + (requestUri.IsDefaultPort ? "" : ":" + requestUri.Port);
Or
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
If you want /blog appended to the last two, add
+ Request.ApplicationPath
Solution 3
// Request.Uri
Uri originalUrl = new Uri("https://www.example.com/blog/currentPage.aspx?id=156");
// www.examle.com
string domain = originalUrl.Host;
// https://www.example.com
string domainUrl = String.Concat(originalUrl.Scheme, Uri.SchemeDelimiter, originalUrl.Host);
Author by
user29964
Updated on August 09, 2020Comments
-
user29964 almost 4 years
I want to retrieve my domain url in asp.net.
for example, if my url is:
http://www.mydomain.com/blog/currentPage.aspx?id=156
I just want the part
http://www.mydomain.com/blog/
can anyone help me out?
-
Ken almost 5 yearsThe only suggestion I would have for this answer to improve it - is to have an example URL and the resulting strings of those URL's via the code examples.
-
Ken almost 5 yearsI like your answer because of the examples that are included! If it was more thorough and more readable it would be even better. Placing your examples either under or above each code for example would be more clear.
-
abatishchev almost 5 years@Ken: sure thing! See the updated version. Is this what you were looking for? Please also note that the answer is 9 years old.
-
Ken almost 5 yearsYes exactly. Sometimes I miss the dates on these things - I need to make it a point to check them. That said - I think your answer is still relevant and the layout clear as to what the result of the code will actually achieve (wish I could up-vote more). Sometimes people declare this will give you blah blah and for sure they know what blah blah 'looks like' and is. Where as someone searching for an answer may be a novice or have no experience in the particular realm of code and have no idea or a bad hunch.