In ASP.NET, what is the quickest way to get the base URl for a request?

Is there a fast way to get the scheme, host, port (only if not 80) and application path in ASP.NET?

As far as I know, I need to assemble the following pieces:

  • Request.Url.Scheme
  • Request.Url.SchemeDelimiter
  • Request.Url.Authority (although that will probably always include the port even when it’s 80)
  • Request.ApplicationPath

Isn’t there a simple property for that?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This should work:

Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath

Note that this may or may not end with a trailing “/” depending on if your app is hosted in the root of the site or in a sub directory.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x