c# - without - razor pages get current url
How to get the URL of the current page in C# (6)
A search landed me at this page, but it wasn't quite what I was looking for. Posting here in case someone else looking for what I was lands at this page too.
There is two ways to do it if you only have a string value.
Same as @Canavar, but you can instantiate a new Uri Object
String URL = "http://localhost:1302/TESTERS/Default6.aspx"; System.Uri uri = new System.Uri(URL);
which means you can use the same methods, e.g.
string url = uri.AbsoluteUri; // http://localhost:1302/TESTERS/Default6.aspx string host = uri.host // localhost
I guess its enough to return absolute path..
Path.GetFileName( Request.Url.AbsolutePath )
Just sharing as this was my solution thanks to Canavar's post.
If you have something like this:
or like this:
and you only want the part that a user would type in then this will work:
String strPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery; String strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");
which would result in these:
Try this :
string url = HttpContext.Current.Request.Url.AbsoluteUri; // http://localhost:1302/TESTERS/Default6.aspx string path = HttpContext.Current.Request.Url.AbsolutePath; // /TESTERS/Default6.aspx string host = HttpContext.Current.Request.Url.Host; // localhost
a tip for people who needs the path/url in global.asax file;
If you need to run this in global.asax > Application_Start and you app pool mode is integrated then you will receive the error below:
Request is not available in this context exception in Application_Start.
In that case you need to use this:
Hope will help others..
if you just want the part between http:// and the first slash
string url = Request.Url.Host;
would return .com if called from this page
Here's the complete breakdown