Do I need to encode attribute values in MVC Razor?

天大地大妈咪最大 提交于 2021-02-19 01:12:42

问题


In a cshtml file, I'm assigning a string to an attribute. For example:

<input name="somename" value="@Model.Value">

Since @Model.Value string could contain any Unicode character, obviously the string must be encoded. Will Razor encode this value automatically? I'm guessing it won't or can't because I could easily put a @Html.Raw immediately after it to break up the whole thing into two tags.

I think what I need to do is this:

<input name="somename" value="@Html.Raw(Html.AttributeEncode(Model.Value))">

Is that correct?

Likewise, if I'm embedding an string value in a JavaScript string in a script, should I use:

//I could use Ajax instead of HttpUtility here, but Ajax just wraps the same call.
<script>$('id').data('key','@Html.Raw(HttpUtility.JavaScriptStringEncode(Model.Value))');</script>

回答1:


Razor performs HTML encoding on strings by default. Depending on where your string is being injected into the HTML stream, this may or may not be the correct encoding to use. If it's not the correct encoding, then you need to perform the correct encoding yourself and be sure to return an MvcHtmlString (i.e. an IHtmlString) to ensure Razor leaves your custom encoding alone.

Since Razor uses HTML encoding, which is technically different from HTML attribute encoding (it's a subset), it's not wrong to use @Html.Raw(Html.AttributeEncode(Model.Value)) to HTML attribute encode the value. At the same time, it's also not necessary, since the default HTML encoding uses the same basic format and will just end up encoding a couple character that otherwise wouldn't need encoded in an HTML attribute value.

On the other hand, in the final case where a string is being injected into the quotes of a JavaScript string, the HTML encoding would absolutely be incorrect, so you'd definitely need to perform the encoding yourself as I did: @Html.Raw(HttpUtility.JavaScriptStringEncode(Model.Value)).




回答2:


Razor automatically encodes it, so you dont need to.

To be specific it is Encoded using HttpUtility Encode / Decode methods and this happens to anything that is not an IHtmlString such as MvcHtmlString.

Encoding it again would be redundant. If you need to escape this behavor, you need to use the Html.Raw helper, which can be a security risk if the user inputs the model value you are rendering.



来源:https://stackoverflow.com/questions/31349297/do-i-need-to-encode-attribute-values-in-mvc-razor

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