In this article, we will learn how to get a URL or extract different parts of URL in ASP.NET Core.
You may at times need to get different parts or values from the URL.
Below is some example that shows different ways of extracting different parts of URL in ASP.NET Core.
How to get a URL or extract different parts of URL in ASP.NET C#
Here, we are using the URL given below to get different values from the URL.
https://localhost:7289/home/privacy?param1=hello¶m2=world¶m3=123
To get the hostname from the URL, you can use the code as given in example:
var HostName = HttpContext.Request.Host.ToString();
//Output ==> localhost:7289
To get the port from the URL, you can use the code as given in example:
var Port = HttpContext.Request.Host.Port.ToString();
//Output ==> 7289
To get the path from the URL, you can use the code as given in the example:
var Path = HttpContext.Request.Path.ToString();
//Output ==> /home/privacy
To get the QueryString from the URL, you can use the code as given in example:
var QueryString = HttpContext.Request.QueryString.ToString();
//Output ==> ?param1=hello¶m2=world¶m3=123
To get the URL scheme(HTTP or HTTPS) from the URL, you can use the code as given in example:
var Scheme = HttpContext.Request.Scheme.ToString();
//Output ==> https
To get the Path with the QueryString from the URL, you need to use the namespace “Microsoft.AspNetCore.Http.Extensions
” and the GetEncodedPathAndQuery()
method, you can use the code as given in example:
var pathWithQueryString = HttpContext.Request.GetEncodedPathAndQuery().ToString();
//Output ==> /home/privacy?param1=hello¶m2=world¶m3=123
To get the complete URL, you need to use the namespace “Microsoft.AspNetCore.Http.Extensions
” and the GetDisplayUrl
()
method, you can use the code as given in example:
var FullURL = HttpContext.Request.GetDisplayUrl().ToString();
//Output ==> https://localhost:7289/home/privacy?param1=hello¶m2=world¶m3=123
And you can also use this code as given below in the example to get the complete URL:
var encodedUrl = HttpContext.Request.GetEncodedUrl().ToString();
//Output ==> https://localhost:7289/home/privacy?param1=hello¶m2=world¶m3=123
I tested the above examples in ASP.NET Core 3.1 or a later version.
I hope this article will help you to understand how to get a URL or extract different parts of a URL in ASP.NET Core.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments