How can I get the baseurl of site?

后端 未结 12 1593
借酒劲吻你
借酒劲吻你 2020-11-30 17:43

I want to write a little helper method which returns the base URL of the site. This is what I came up with:

public static string GetSiteUrl()
{
    string ur         


        
相关标签:
12条回答
  • 2020-11-30 17:56

    I go with

    HttpContext.Current.Request.ServerVariables["HTTP_HOST"]
    
    0 讨论(0)
  • 2020-11-30 17:57

    Try this:

    string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + 
        Request.ApplicationPath.TrimEnd('/') + "/";
    
    0 讨论(0)
  • 2020-11-30 17:58
    string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority)
    

    That's it ;)

    0 讨论(0)
  • 2020-11-30 18:07

    I'm using following code from Application_Start

    String baseUrl = Path.GetDirectoryName(HttpContext.Current.Request.Url.OriginalString);

    0 讨论(0)
  • 2020-11-30 18:10

    The popular GetLeftPart solution is not supported in the PCL version of Uri, unfortunately. GetComponents is, however, so if you need portability, this should do the trick:

    uri.GetComponents(
        UriComponents.SchemeAndServer | UriComponents.UserInfo, UriFormat.Unescaped);
    
    0 讨论(0)
  • 2020-11-30 18:11

    Based on what Warlock wrote, I found that the virtual path root is needed if you aren't hosted at the root of your web. (This works for MVC Web API controllers)

    String baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority) 
    + Configuration.VirtualPathRoot;
    
    0 讨论(0)
提交回复
热议问题