Can't get site root url in asp mvc

前端 未结 5 1134
伪装坚强ぢ
伪装坚强ぢ 2020-12-30 21:13

I need to get site root url in razor page in javascript code:

...
var siteRootUrl = \'@Url.Content(\"~\")\';
...

But all I get from this is

相关标签:
5条回答
  • 2020-12-30 21:19

    @Url.Content() returns the root RELATIVE path, that is the path from the root of the domain.

    So if your site was at www.foo.com/site then Url.Content() returns /site

    Ishmael's response is correct. You will need to parse a full url.

    0 讨论(0)
  • 2020-12-30 21:20

    Easiest way I know to get AbsoluteUri would be

    @Url.Action("", null, null, "http")
    
    0 讨论(0)
  • 2020-12-30 21:22

    To get the current host with port (mysite.com, www.mysite.com or localhost:9876)

     Request.Url.Authority
    

    To get your current application folder: (/ or /appfolder/)

     Url.Content("~/")
    

    To mix them?

     String.Format("{0}://{1}{2}",Request.Url.Scheme, Request.Url.Authority,Url.Content("~/"))
    

    OR (As torm pointed out)

     Url.Action("", null, null, Request.Url.Scheme)
     Url.Action("", null, null, "http")
     Url.Action("", null, null, "https") 
    

    To generate an Action URL:

     Url.Action("About","Home",null,"http")
    
    0 讨论(0)
  • 2020-12-30 21:30

    For the full URL, use @Request.Url.ToString().

    You can either parse that, or use one of the other methods on the HttpRequest.Url property, which is a System.Uri object.

    http://msdn.microsoft.com/en-us/library/system.uri.aspx

    0 讨论(0)
  • 2020-12-30 21:36

    The @Url.Content is returning the relative URL which is correct. The following code gives you various option in getting a URL realtive via code, absolute Url via code, absolute via javascript:

    <div>Site 'Relative Url = '@Url.Content("~")'</div>
    <div>Site 'Absolute Url = '@System.Web.HttpContext.Current.Request.Url.AbsoluteUri'</div>
    
    <script type="text/javascript">
        alert("site URL via js = " + location.href);
    </script>
    

    You will get something like:

    Site 'Relative Url = '/' Site 'Absolute Url = 'http://localhost:14763/'

    and also the JS alert showing the href/absolute Url

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