How can I get the root domain URI in ASP.NET?

后端 未结 14 1433
庸人自扰
庸人自扰 2020-12-12 16:15

Let\'s say I\'m hosting a website at http://www.foobar.com.

Is there a way I can programmatically ascertain \"http://www.foobar.com/\" in my code behind (i.e. witho

相关标签:
14条回答
  • 2020-12-12 16:38

    This will return specifically what you are asking.

    Dim mySiteUrl = Request.Url.Host.ToString()
    

    I know this is an older question. But I needed the same simple answer and this returns exactly what is asked (without the http://).

    0 讨论(0)
  • 2020-12-12 16:40
    string host = Request.Url.Host;
    Regex domainReg = new Regex("([^.]+\\.[^.]+)$");
    HttpCookie cookie = new HttpCookie(cookieName, "true");
    if (domainReg.IsMatch(host))
    {
      cookieDomain = domainReg.Match(host).Groups[1].Value;                                
    }
    
    0 讨论(0)
  • 2020-12-12 16:43

    C# Example Below:

    string scheme = "http://";
    string rootUrl = default(string);
    if (Request.ServerVariables["HTTPS"].ToString().ToLower() == "on")
    {
      scheme = "https://";
    }
    rootUrl = scheme + Request.ServerVariables["SERVER_NAME"].ToString();
    
    0 讨论(0)
  • 2020-12-12 16:45

    HttpContext.Current.Request.Url can get you all the info on the URL. And can break down the url into its fragments.

    0 讨论(0)
  • 2020-12-12 16:45

    If example Url is http://www.foobar.com/Page1

    HttpContext.Current.Request.Url; //returns "http://www.foobar.com/Page1"
    
    
    HttpContext.Current.Request.Url.Host; //returns "www.foobar.com"
    
    
    HttpContext.Current.Request.Url.Scheme; //returns "http/https"
    
    
    HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority); //returns "http://www.foobar.com"
    
    0 讨论(0)
  • 2020-12-12 16:45

    This works also:

    string url = HttpContext.Request.Url.Authority;

    0 讨论(0)
提交回复
热议问题