开发者

MVC2 Custom HTML Helper and <%: %> Syntax

开发者 https://www.devze.com 2023-01-15 17:16 出处:网络
Is there any way to use a custom html helper with the <%: %> syntax ? I know that if i\'m use the code below, it\'s ok, but it\'s seems not so e开发者_开发技巧legant and secure.

Is there any way to use a custom html helper with the <%: %> syntax ?

I know that if i'm use the code below, it's ok, but it's seems not so e开发者_开发技巧legant and secure.

<%= Html.MyHelper("Some Data")%>

I mean, use <%= %> is the best practices?


Have your helper return an MvcHtmlString instead of a string. Also, please use <%: as much as possible.


HTML helpers create HTML, which is normally expected to be output raw with <%= %>. If you used <%: %> to HTML-escape the output of an HTML helper, you'll see the HTML source it produced on the page as text (eg literally <input name="foo" value="bar"> on-screen), which is probably not what you want.

It is up to the helper to HTML-escape any text content inside them, for safety. Yes, if you write a custom HTML helper and get it wrong—forgetting to HTML-encode strings your helper is putting in text content or attribute values in the output—you'll have security holes. You need to know what you're doing with escaping to write an HTML helper.

Microsoft, unfortunately, apparently don't, as the very first example in their tutorial completely fails:

return String.Format("<label for='{0}'>{1}</label>", target, text);

Whoops. Hope those ID and text strings didn't come from untrusted data!

[why are web tutorials always so lamentably terrible at escaping issues?]

0

精彩评论

暂无评论...
验证码 换一张
取 消