简体   繁体   English

带有Url.Content助手的Razor在URL中的空格处结束引号

[英]Razor with Url.Content helper is ending quotes at space in URL

I'm using ASP.NET Core 2 with Razor to try and pass an image URL into the View via a ViewModel. 我将ASP.NET Core 2与Razor结合使用,以尝试通过ViewModel将图像URL传递到View中。 Unfortunately, the image URL has spaces in it, which I don't have control over at the moment. 不幸的是,图像URL中有空格,目前我无法控制。

I have a file name like this (note the space): 我有一个这样的文件名(注意空格):

https://example.com/images/file name.jpg

I'm using Razor to try and show the image like this: 我正在使用Razor尝试显示如下图像:

<img src=@item.ImageUrl />

The output HTML looks like this: 输出的HTML看起来像这样:

<img src="https://example.com/images/file" name.jpg />

Obviously this will not do! 显然这不会做! I should mention, we know this all works when we use an image that has no spaces in the file name. 我应该提到,当我们使用文件名中没有空格的图像时,这一切都知道。 Here are some ways I've tried to correct the issue: 这是我尝试解决此问题的一些方法:

Using Url.Content helper in Razor (this did not make a difference): 在Razor中使用Url.Content帮助程序(这没​​有什么不同):

<img src=@Url.Content(item.ImageUrl) />

Using System.Web.HttpUtility.UrlEncode when populating the ViewModel (this results in a "double-encoding" error): 在填充ViewModel时使用System.Web.HttpUtility.UrlEncode (这会导致“双重编码”错误):

myViewModel.ImageUrl = HttpUtility.UrlEncode(someUrl);

My goal is to get the URL encoded properly (no "double-encoding" and no truncating at the space in the input string). 我的目标是使URL正确编码(在输入字符串的空格中没有“ double-encoding”并且不被截断)。 How can I achieve this goal? 我怎样才能实现这个目标?

The problem is that Razor will attempt to create valid HTML, so when it sees a space it automatically closes the quotation marks, so: 问题是Razor会尝试创建有效的HTML,因此当看到空格时,它将自动关闭引号,因此:

@{string img = "a a.jpg";}
<img src=@img />

Gets rendered as 获取呈现为

<img src="a "a.jpg /> // of course invalid

So, you need to be sure you include your quotation marks, then Razor will use them: 因此,您需要确保添加引号,然后Razor会使用它们:

<img src="@img" />

Which gets rendered as 哪个被渲染为

<img src="a a.jpg" />

You can try 你可以试试

<img src="@Html.Raw(item.ImageUrl)" />

but I agree that using invalid URLs (with spaces) doesn't seem very useful in the long run. 但我同意,从长远来看,使用无效的URL(带空格)似乎不太有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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