4

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
user29964
  • 15,740
  • 21
  • 56
  • 63

3 Answers3

13

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
Sander Versluys
  • 72,737
  • 23
  • 84
  • 91
  • 1
    I thinks you'r answer is the best. Just it's better to use String.Concat and Request.ApplicationPath is already a string. – abatishchev Mar 16 '09 at 08:38
  • The 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 Aug 08 '19 at 23:42
6
// 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);
abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • I 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. – Ken Aug 08 '19 at 23:44
  • @Ken: sure thing! See the updated version. Is this what you were looking for? Please also note that the answer is 9 years old. – abatishchev Aug 09 '19 at 06:55
  • Yes 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. – Ken Aug 10 '19 at 04:44
3

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.

Community
  • 1
  • 1
Canavar
  • 47,715
  • 17
  • 91
  • 122