asp.net core tilde slash (~/) not resolving image path

≯℡__Kan透↙ 提交于 2020-05-14 05:55:17

问题


I have some markup in my Index.cshtml view, which has an inline css style with the background-image property. When the page is rendered the correct path of the image is not being generated and the tilde remains in the url

HTML Markup:

The path that is used on the img tag works properly when the page is rendered, but the path in the background-image property displays like this and the image is not found

Rendered Markup:

<article class="card-item card-item-colored" style="background-image:url(~/build/images/11.jpg);">
                <img class="card-item-pic" src="/build/images/11.jpg" alt="">
                <div class="card-item-hover">
                    <a href="#" class="btn btn-inverse-colored">View Demo</a>
                </div>
                <header class="card-item-caption">
                    <h4>Login Page</h4>
                </header>
            </article>

回答1:


Inside a style property, url(...) is a CSS function not a Razor method.

In the CSS url(...) function, start with a forward slash / not a tilda ~ to make a URI relative to the root of your site:

<article style="background-image:url(/build/images/11.jpg);">

The CSS 2.1 specification specifies this in section 4.3.4 URLs and URIs and refers to RFC 3986 for details, which states:

A relative reference that begins with a single slash character is termed an absolute-path reference.




回答2:


The use of the tilde (~) in @Url.Content(), and elsewhere in Razor code, will be translated by ASP.NET to reference the root of the current application.

If you use the tilde directly in a string expression, such as within background-image: url() it is not interpreted (parsed) by ASP.NET, and so appears directly as is in the HTML or CSS that is output. This doesn't work because ~ is not a feature of HTML or CSS.



来源:https://stackoverflow.com/questions/45526620/asp-net-core-tilde-slash-not-resolving-image-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!