【问题标题】:How to get the URL from browser in ASP.Net MVC 5 Application如何在 ASP.Net MVC 5 应用程序中从浏览器获取 URL
【发布时间】: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


【解决方案1】:

这将为您提供完整的 URL:

var url = Request.RequestContext.HttpContext.Request.RawUrl;

【讨论】:

    【解决方案2】:

    Uri.Authority 会给你主机名和端口(如果 URL 有的话)。

    获取域名系统 (DNS) 主机名或 IP 地址和端口 服务器的编号。

    // 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);
    

    因此,在您的情况下,您只需使用以下内容:

    HttpContext.Current.Request.Url.Authority
    

    【讨论】:

    • 非常感谢。我会记得“SO禁止无知”:) :D :D
    猜你喜欢
    • 1970-01-01
    • 2011-04-04
    • 2011-08-04
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    相关资源
    最近更新 更多