简体   繁体   English

如何从ASP.Net MVC 5应用程序中的浏览器获取URL

[英]How to get the URL from browser in ASP.Net MVC 5 Application

I have ASP.Net web application, and I want to fetch the URL present in the browser. 我有ASP.Net Web应用程序,并且想获取浏览器中存在的URL。 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 方案1.网址: https//sample.com-工作正常, host variable获取sample.com

Scenario 2. Url: https://sample.com:2345 - host variable just fetches sample.com instead of sample.com:2345 方案2。网址: httpssample.comsample.com:2345 host variable仅获取sample.com而不是sample.com:2345

Work Around (temp fix: hard code 2345 in the result) 解决方法(临时修复:结果中包含硬编码2345)

 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). Uri.Authority将为您提供主机名和端口(如果URL有一个)。

Gets the Domain Name System (DNS) host name or IP address and the port number for a server. 获取域名系统(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);

So in your case, you would just use the following: 因此,在您的情况下,您将只使用以下内容:

HttpContext.Current.Request.Url.Authority

这将为您提供完整的URL:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM