【发布时间】:2017-05-12 04:07:15
【问题描述】:
我有 ASP.Net Web 应用程序,我想获取浏览器中的 URL。以下是我的尝试
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;
}
}
场景 1. 网址:https://sample.com - 工作正常,host variable 获取 sample.com
场景 2. 网址:https://sample.com:2345 - host variable 只是获取 sample.com 而不是 sample.com:2345
解决方法(临时修复:结果中的硬代码 2345)
string result = "https://" + host + ":2345" + url.Action("LoginSettingsSubmit", "Security");
但我正在寻找一个没有硬编码的万无一失的解决方案。另外,如果我可以在不更改已经编写的代码中的大量内容的情况下实现结果,那就太好了。
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;
}
}
【问题讨论】:
-
为什么你只为
localhost设置host到Url.Authority?为什么不一直使用Url.Authority?在场景 1 中,如果Host的 sample.com 是 abc.com,我会感到惊讶。 -
我只是一个初学者。原谅我的无知。我会尽力按照你说的去做,如果我得到了我想要的,我会告诉你的。
-
abc 是一个错字。谢谢。修好了。
-
@Unbreakable 你是不是要根据 Action 方法名和控制器名来构造 URL?
-
其实是google认证的重定向。我的动作名称和控制器名称不是动态的。如果这就是你的意思。实际上,我需要将操作和控制器名称附加到 URL,以便当 google 验证登录时,我需要再次点击
HTTPOST方法,该方法接收 google 验证服务返回的代码。
标签: c# asp.net-mvc asp.net-mvc-4 url asp.net-mvc-5