什么是 MvcHtmlString,我应该什么时候使用它? [英] What is an MvcHtmlString and when should I use it?

查看:57
本文介绍了什么是 MvcHtmlString,我应该什么时候使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档MvcHtmlString 的 a> 并不是很有启发性:

The documentation for MvcHtmlString is not terribly enlightening:

表示不应再次编码的 HTML 编码字符串.

Represents an HTML-encoded string that should not be encoded again.

我不清楚这到底意味着什么.似乎一些 HTML 帮助器方法返回一个 MvcHtmlString,但我在网上看到的几个自定义帮助器示例只返回一个常规字符串.

It's not clear to me what exactly the implications of this are. It seems that some HTML helper methods return an MvcHtmlString, but several examples I've seen online of custom helpers just return a regular string.

问题:

什么是MvcHtmlString?

我什么时候应该选择 MvcHtmlString 而不是 string,反之亦然?为什么?

When should I choose MvcHtmlString over string and vice versa? Why?

推荐答案

ASP.NET 4 引入了新的代码块语法 <%: %>.本质上,<%: foo %> 转换为 <%= HttpUtility.HtmlEncode(foo) %>.该团队正试图让开发人员尽可能使用 <%: %> 而不是 <%= %> 来防止 XSS.

ASP.NET 4 introduces a new code nugget syntax <%: %>. Essentially, <%: foo %> translates to <%= HttpUtility.HtmlEncode(foo) %>. The team is trying to get developers to use <%: %> instead of <%= %> wherever possible to prevent XSS.

然而,这引入了一个问题,如果代码块已经对其结果进行了编码,<%: %> 语法将对其进行重新编码.这是通过引入 IHtmlString 接口(.NET 4 中的新功能)解决的.如果 <%: foo() %> 中的 foo() 返回 IHtmlString,则 <%: %> 语法不会重新编码.

However, this introduces the problem that if a code nugget already encodes its result, the <%: %> syntax will re-encode it. This is solved by the introduction of the IHtmlString interface (new in .NET 4). If the foo() in <%: foo() %> returns an IHtmlString, the <%: %> syntax will not re-encode it.

MVC 2 的助手返回 MvcHtmlString,它在 ASP.NET 4 上实现了接口 IHtmlString.因此,当开发人员在 ASP.NET 4 中使用 <%: Html.*() %> 时,结果不会被双重编码.

MVC 2's helpers return MvcHtmlString, which on ASP.NET 4 implements the interface IHtmlString. Therefore when developers use <%: Html.*() %> in ASP.NET 4, the result won't be double-encoded.

这种新语法的直接好处是您的视图更简洁一些.例如,您可以编写 <%: ViewData["anything"] %> 而不是 <%= Html.Encode(ViewData["anything"]) %>.

An immediate benefit of this new syntax is that your views are a little cleaner. For example, you can write <%: ViewData["anything"] %> instead of <%= Html.Encode(ViewData["anything"]) %>.

这篇关于什么是 MvcHtmlString,我应该什么时候使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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