How can I get the baseurl of site?

后端 未结 12 1645
借酒劲吻你
借酒劲吻你 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:53

    To me, @warlock's looks like the best answer here so far, but I've always used this in the past;

    string baseUrl = Request.Url.GetComponents(
        UriComponents.SchemeAndServer, UriFormat.UriEscaped)   
    

    Or in a WebAPI controller;

    string baseUrl = Url.Request.RequestUri.GetComponents(
        UriComponents.SchemeAndServer, UriFormat.Unescaped)
    

    which is handy so you can choose what escaping format you want. I'm not clear why there are two such different implementations, and as far as I can tell, this method and @warlock's return the exact same result in this case, but it looks like GetLeftPart() would also work for non server Uri's like mailto tags for instance.

提交回复
热议问题