简体   繁体   中英

@Url.Content and @Href not working correctly when URL is rewritten

@Url.Content and @Href helper methods in ASP.NET MVC are not working correctly in one situation. This is situation when on localhost, and it is hosted in IIS rather than on IIS Express so URL looks like something: http://localhost/MyApp/index-hr instead of for example http://localhost:12345/index-hr . This is how I call my script:

   <script src='@Href("~/Scripts/toastr/toastr.js")' type="text/javascript">       </script>

I also tried:

    <script src='@Url.Content("~/Scripts/toastr/toastr.js")' type="text/javascript"></script>, 

and:

     <script src='~/Scripts/toastr/toastr.js' type="text/javascript"></script>

It resolves Url great except situation when URL is something like : http://localhost/MyApp/index-hr . My URL /index-hr is rewritten and maps to controller Home , and action HomeIndex . I noticed that it resolves OK when URL is http://localhost/MyApp/Home , so maybe it is not problem because of extra slash(when app is hosted on local IIS) but because URL is rewritten. Other pages with rewitten URL load toast.js OK but they have deeper links , but in this situation it resolves toast.js to this URL: http://localhost/Scripts/toastr/toastr.js which result in 404 ofcourse. It should resolve to: http://localhost/MyApp/Scripts/toastr/toastr.js

I am not sure if I found solution or just fixed this thing and messed other things but as suggested here I wrote this code is global.asax:

   protected void Application_BeginRequest()
    {

        Context.Items["IIS_WasUrlRewritten"] = false;
    }

It says here that Tilde (~) notation maps to the original URLs by using IIS URL rewrite in ASP.NET Web Pages Razor V3. In case URL will not work in future here is explanation:

This issue occurs because the behavior of tilde notation in URLs is changed in Web Pages Razor V3 for consistency with ASP.NET MVC. In ASP.NET MVC, the tilde notation in the Url.Content method or the Html.ActionLink method produces the original URLs regardless of the IIS URL rewrite rules.

However, in Web Pages Razor V2, the tilde notation in URLs maps to the rewritten URLs when the IIS URL rewriting module is enabled. For example, when the requests under content.asp.net are rewritten to the URL under asp.net/content/, the href attribute in is resolved to /content/book/. In Web Pages Razor V3, the same href attribute is translated into /book/, which is the original URL in the browser.

It was better in razor v2 than in razor v3?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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