解析相对于应用程序根的图像 uri

Resolving an image uri relative to application root

我正在使用 Asp.Net MVC 5。对于这个问题,假设我的应用程序是由 localhost:9000/app.

提供的

我的 _layout.cshtml:

<img src="@Url.Content("~/Content/logo.png")" />

当用户请求localhost:9000/app/foobar时,图片URI被正确解析为localhost:9000/app/Content/logo.png

但是当用户请求 localhost:9000/app/folder/bender_is_great 时,图像 URI 解析为 localhost:9000/app/folder/Content/logo.png

如何让图像 URI 始终相对于应用程序根而不是相对于请求的路径进行解析?

编辑:Server.MapPath("~/Content/logo.png") 有同样的问题。它是相对于请求的路径解析的,而不是应用程序根目录。

结果是我的 URL 重写了友好 HTML5 URL 的规则,没有 hashbang (#!)。重写引擎在应用程序上设置了一个项目:"IIS_WasUrlRewritten"Url.Content(...) calls into UrlUtil, which pays attention to this item and changes its behavior. This Microsoft Support page 说:

To resolve the tilde notation to the rewritten URLs by using the same behavior as in Web Pages Razor V2, set the IIS_WasUrlRewritten context to false in each Web page or in Application_BeginRequest in Global.asax for the global setting as follows:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    Context.Items["IIS_WasUrlRewritten"] = false;
}

Note The change of the IIS_WasUrlRewritten context affects the tilde notation not only in the HTML elements, but also in the MVC helper methods. For example, if it is set to false, the tilde notation in Url.Content and Html.ActionLink returns the rewritten URLs.

到目前为止,这段代码没有在我的应用程序中引起任何问题并且已经解决了问题。