简体   繁体   English

HTML解码和编码

[英]HTML Decode and Encode

I have tried to decode the html text that i have in the databse in my MVC 3 Razor application. 我试图对我的MVC 3 Razor应用程序中的数据库中的html文本进行解码。 the html text in the databse is not encoded. 数据库中的html文本未编码。 I tries httpUtility.decode , server.decode but none of them work. 我尝试httpUtility.decode,server.decode,但是它们都不起作用。 finally i managed to make it work with Html.raw(string) 最后我设法使其与Html.raw(string)

sample of non working code 非工作代码示例

@Server.HtmlDecode(item.ShortDescription)
@HttpUtility.HtmlDecode(item.ShortDescription)

Do you know why we can not use html.decode in my case ! 您知道为什么我不能使用html.decode吗!

I thought this would save some one else from looking for few hours. 我以为这样可以节省几个小时的时间。

It works just fine to decode the text, but then it will automatically be encoded again when it's put in the page using the @ syntax. 它可以很好地解码文本,但是当使用@语法将其放入页面时,它将自动再次进行编码。

The Html.Raw method wraps the string in an HtmlString , which tells the razor engine not to encode it when it's put in the page. Html.Raw方法将字符串包装在HtmlString ,这告诉剃刀引擎在将其放入页面时不要对其进行编码。

If you want to display the value as-is without any HTML encoding you could use the Html.Raw helper: 如果您想按原样显示值而没有任何HTML编码,则可以使用Html.Raw帮助器:

@Html.Raw(item.ShortDescription)

Be warned thought that by doing this you are opening your site to XSS attacks so you should be very careful about what HTML this ShortDescription property contains. 警告您,这样做会使您的网站受到XSS攻击,因此您应该非常小心此ShortDescription属性包含的HTML。 If it is the user that enters it you should absolutely ensure that it is safe. 如果是用户输入,则应绝对确保它是安全的。 You could use the AntiXss library for this. 您可以为此使用AntiXss库

Do you know why we can not use html.decode in my case ! 您知道为什么我不能使用html.decode吗!

Because Html.Decode returns a string and when you feed a string to the @() Razor function it automatically Html encodes it again and ruins your previous efforts. 因为Html.Decode返回一个字符串,并且当您将字符串提供给@() Razor函数时,它会自动由Html再次对其进行编码,并破坏您以前的工作。 That's why the Html.Raw helper exists. 这就是Html.Raw助手存在的原因。

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

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