I have ASP.Net web application, and I want to fetch the URL present in the browser. Below is my attempt
public static string UrlForGoogleAuth
{
get
{
UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
string host = HttpContext.Current.Request.Url.Host;
if (host == "localhost")
{
host = HttpContext.Current.Request.Url.Authority;
}
string result = "https://" + host + url.Action("LoginSettingsSubmit", "Security");
return result;
}
}
Scenario 1. Url: https://sample.com - works fine and host variable
fetches sample.com
Scenario 2. Url: https://sample.com:2345 - host variable
just fetches sample.com
instead of sample.com:2345
Work Around (temp fix: hard code 2345 in the result)
string result = "https://" + host + ":2345" + url.Action("LoginSettingsSubmit", "Security");
But I am looking for a fool proof solution with no hard-coding. Also, If I can achieve the result without changing alot of stuff in already written code, then that would be great.
EDIT:
public static string UrlForGoogleAuth
{
get
{
UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
host = HttpContext.Current.Request.Url.Authority;
string result = "https://" + host + url.Action("LoginSettingsSubmit", "Security");
return result;
}
}
Uri.Authority
will give you the host name and port (if the URL has one).
Gets the Domain Name System (DNS) host name or IP address and the port number for a server.
// www.sample.com:8080
Console.WriteLine(new Uri("https://www.sample.com:8080/controller/action").Authority);
// www.sample.com
Console.WriteLine(new Uri("https://www.sample.com/controller/action").Authority);
So in your case, you would just use the following:
HttpContext.Current.Request.Url.Authority
这将为您提供完整的URL:
var url = Request.RequestContext.HttpContext.Request.RawUrl;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.