Hey! Let’s take a look at how you can get the current asp.net URL. Good news! It could not be easier! Let’s go!
In ASP.NET, we can use the Request. Url property to get the URL. The Url property is an instance of the Uri class, which provides various properties and methods for working with URLs. There are a couple of ways you can go about this depending on what exactly you need. All of them are quick and easy one-liners so no sweat.
Most popular way to get current URL in asp.net
pick all the pieces you need and combine them into a string. If you need the whole URL then use this:
string currentUrl = $"{Request.Scheme}://{Request.Host}{Request.PathBase}{Request.Path}{Request.QueryString}"
If you only need the base URL without path and query then leave PathBase
, Path
, and QueryString parameter from the string
string rawUrl = $"{Request.Scheme}://{Request.Host}"
Using UniHelper library
Here you can use:
GetDisplayUrl()
Returns the combined components of the request URL in a fully un-escaped form (except for the QueryString) suitable only for display. This format should not be used in HTTP headers or other HTTP operations.
GetEncodedUrl()
Returns the combined components of the request URL in a fully escaped form suitable for use in HTTP headers and other HTTP operations.
using Microsoft.AspNetCore.Http.Extensions;
string url = HttpContext.Request.GetDisplayUrl();
// or
string url = HttpContext.Request.GetEncodedUrl();
Of course, there are other ways that you can use to get the current URL in asp.net. But these two will most definitely work.
Thanks for reading.