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.
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
http://localhost:1345/app/homepage.aspx?query1=a&query2=b
string path = HttpContext.Current.Request.Url.AbsolutePath;
The path string variable will return “/app/homepage.aspx”.
string host = HttpContext.Current.Request.Url.Host;
The host string variable will return “localhost”.
string authority = HttpContext.Current.Request.Url.Authority
The authority string variable will return “localhost:1345”.
string port = HttpContext.Current.Request.Url.Port
The port string variable will return “1345”.
string app_path = HttpContext.Current.Request.ApplicationPath
The app_path string will return “/app”.
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:
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!
In 2024 we're witnessing a critical point in democratic technology: the integration of blockchain and…
We’re thrilled to announce an exciting opportunity for you to win not one but two…
Acquiring practical skills is crucial for career advancement and personal growth. Education Ecosystem stands out…
Artificial Intelligence (AI) has been making significant strides in various industries, and the software development…
Another week to bring you the top yield platforms for three of the most prominent…
If you hold a large volume of LEDU tokens above 1 million units and wish…
View Comments
Sweet and simple way. I understood this very easily.