是否JsonConvert.SerializeObject的输出必须在连接的Razor视图codeD? [英] Does the output of JsonConvert.SerializeObject need to be encoded in Razor view?

查看:361
本文介绍了是否JsonConvert.SerializeObject的输出必须在连接的Razor视图codeD?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Newtonsoft库为C#对象转换成JSON。这是使用 Newtonsoft.Json.JsonConvert.SerializeObject 的安全,还是需要额外的编码?如果需要额外的编码,你有什么建议?

下面是我如何使用它在的Razor视图:

 <脚本类型=文/ JavaScript的>
    VAR jsModel = @ Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(型号))
< / SCRIPT>


解决方案

您最起码需要执行的额外编码'<'字符'\\ u003C'和'>'字符'\\ u003E'。上次我检查JSON.NET在字符串中没有连接code这些字符。

我可能会得到高射炮这一点,但我会做到这一点的方法是呈现一个虚拟的元素到页面:

 < D​​IV ID =的-DIV数据的json =@ JsonConvert.SerializeObject(型号)/>

然后,在Javascript中,提取出的数据JSON 的从属性值的的-DIV 的元素和 JSON.parse 它。这样做的好处是,你不必担心哪些字符需要特殊的编码。在 SerializeObject 方法的担保的JSON BLOB是良好的,而 @ 运营商任何剩余的非HTML安全字符从JSON的转换被放进HTML属性之前进行正确转义遗留担保(只要属性值被双引号包围,如上)。所以,是的,这是一个有点难看,但它是有效的在完全关闭整个类的漏洞。

I use the Newtonsoft library to convert C# objects into JSON. Is this use of Newtonsoft.Json.JsonConvert.SerializeObject secure, or is additional encoding necessary? If additional encoding is needed, what do you suggest?

Here is how I use it in a Razor view:

<script type="text/javascript">
    var jsModel = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))
</script>

解决方案

You will at the very least need to perform additional encoding of the '<' character to '\u003C' and the '>' character to '\u003E'. Last I checked JSON.NET did not encode these characters in string literals.

I'm probably going to get flak for this, but the way I would do this is to render a dummy element onto the page:

<div id="the-div" data-json="@JsonConvert.SerializeObject(Model)" />

Then, in Javascript, extract the data-json attribute value from the the-div element and JSON.parse it. The benefit to this is that you don't need to worry about which characters require special encoding. The SerializeObject method guarantees that the JSON blob is well-formed, and the @ operator guarantees that any remaining non-HTML-safe characters left over from the JSON conversion are properly escaped before being put into the HTML attribute (as long as the attribute value is surrounded by double quotes, as above). So yes, it's a little uglier, but it is effective at completely shutting down an entire class of vulnerabilities.

这篇关于是否JsonConvert.SerializeObject的输出必须在连接的Razor视图codeD?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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