If you are using C# for creating apps, you may want to use it to fetch the URL of the current page. This requirement is extremely common in web apps, or apps that take advantage of external or internal resources. In this tutorial, we will cover how to get the URL of the current page using C#. Without wasting much time, let’s gets started.
1 |
string url = HttpContext.Current.Request.Url.AbsoluteUri; |
This will return the absolute URL. www.google.com, for example, or it will return localhost URL if you are in the local environment.
It should be kept in mind that Url.AbsoluteUri does return anything after the “#” symbol.
When working on an app, you might also want to get different results for different purposes. Let’s go through them, one by one.
We will use a hypothetical URL to work. Let it be
1 |
http://localhost:1345/app/homepage.aspx?query1=a&query2=b |
1 |
string path = HttpContext.Current.Request.Url.AbsolutePath; |
The path string variable will return “/app/homepage.aspx”.
1 |
string host = HttpContext.Current.Request.Url.Host; |
The host string variable will return “localhost”.
1 |
string authority = HttpContext.Current.Request.Url.Authority |
The authority string variable will return “localhost:1345”.
1 |
string port = HttpContext.Current.Request.Url.Port |
The port string variable will return “1345”.
1 |
string app_path = HttpContext.Current.Request.ApplicationPath |
The app_path string will return “/app”.
1 |
string path_and_query = HttpContext.Current.Request.Url.PathAndQuery |
The path_and_query string will return “/app/homepage.aspx?query1=a&query2=b”.
As you can see, you can get different parts of the URL according to your requirement. Just make sure you store the variable correctly and don’t use concatenation to get different parts of the URL.
You can read more about URL properties here.
If you feel stuck and need more help regarding this function, you can post your queries in the comment section below.
You can also check on our website videos about C#. Below are some examples:
- Galactic Tactical Fighters Online #gamedev (part 79) – C#
- C# Unity5 Quake Multiplayer FPS (part 4) – C#
You can also follow some of our broadcasters who program in C#, as below:
Another cool way to find out interesting things about C# is to access our project page!