解析相对于应用程序根目录的图像uri [英] Resolving an image uri relative to application root

查看:44
本文介绍了解析相对于应用程序根目录的图像uri的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Asp.Net MVC5.为此问题假设我的应用程序是从 localhost:9000/app 提供服务的.

I am using Asp.Net MVC 5. Assume for this question that my application is being served from localhost:9000/app.

我已经在我的 _layout.cshtml 中找到了它:

I've got this in my _layout.cshtml:

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

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

When the user requests localhost:9000/app/foobar, the image URI is correctly resolved to localhost:9000/app/Content/logo.png.

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

But when the user requests localhost:9000/app/folder/bender_is_great, the image URI resolves to localhost:9000/app/folder/Content/logo.png.

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

How do I get the image URI to always resolve relative to the application root, not relative to the requested path?

Server.MapPath(〜/Content/logo.png")具有相同的问题.它是相对于请求的路径而不是应用程序根目录进行解析的.

Server.MapPath("~/Content/logo.png") has the same issue. It's resolving relative to the requested path, not the application root.

推荐答案

原来是我的URL重写规则,用于不带井号(#!)的友好HTML5 URL.重写引擎在应用程序上设置了一个项目:"IIS_WasUrlRewrite" . Url.Content(...)调用 UrlUtil ,它会注意此项目并更改其行为. Microsoft支持页面说:

Turns out it was my URL rewrite rules for friendly HTML5 URLs without the hashbang (#!). The rewriting engine set an item on the application: "IIS_WasUrlRewritten". Url.Content(...) calls into UrlUtil, which pays attention to this item and changes its behavior. This Microsoft Support page says:

要通过使用与Web页Razor V2中相同的行为来将波浪符号表示为重写的URL,请在每个Web页面或Global.asax中的Application_BeginRequest中将IIS_WasUrlRewrite上下文设置为false,以进行全局设置,如下所示:

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

注意IIS_WasUrlRewrite上下文的更改不仅影响HTML元素中的波浪符号,而且影响MVC帮助器方法中的波浪符号.例如,如果将其设置为false,则Url.Content和Html.ActionLink中的波浪号表示法将返回重写的URL.

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.

到目前为止,此代码尚未在我的应用程序中引起任何问题,并已解决了该问题.

So far this code hasn't caused any problems in my application and has resolved the issue.

这篇关于解析相对于应用程序根目录的图像uri的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆