如何使用Razor将未编码的Json写入我的View?

时间:2010-11-01 20:24:31

标签: asp.net-mvc json razor

我正在尝试使用Razor将对象作为JSON写入我的Asp.Net MVC View,如下所示:

<script type="text/javascript">
  var potentialAttendees = @Json.Encode(Model.PotentialAttendees);
</script>

问题是在输出中JSON是编码的,我的浏览器不喜欢它。例如:

<script type="text/javascript">
    var potentialAttendees = [{&quot;Name&quot;:&quot;Samuel Jack&quot;},];
</script>

如何让Razor发出未编码的JSON?

3 个答案:

答案 0 :(得分:185)

你这样做:

@Html.Raw(Json.Encode(Model.PotentialAttendees))

在早于Beta 2的版本中,您可以这样做:

@(new HtmlString(Json.Encode(Model.PotentialAttendees)))

答案 1 :(得分:40)

Newtonsoft JsonConvert.SerializeObject的行为与Json.Encode的行为不同,并且执行@ david-k-egghead建议的行为可以让您进行 XSS攻击

将此代码放入Razor视图中,以确保使用Json.Encode是安全的,并且可以在JavaScript上下文中使Newtonsoft变得安全,但不是没有额外的工作。

<script>
    var jsonEncodePotentialAttendees = @Html.Raw(Json.Encode(
        new[] { new { Name = "Samuel Jack</script><script>alert('jsonEncodePotentialAttendees failed XSS test')</script>" } }
    ));
    alert('jsonEncodePotentialAttendees passed XSS test: ' + jsonEncodePotentialAttendees[0].Name);
</script>
<script>
    var safeNewtonsoftPotentialAttendees = JSON.parse(@Html.Raw(HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(
        new[] { new { Name = "Samuel Jack</script><script>alert('safeNewtonsoftPotentialAttendees failed XSS test')</script>" } }), addDoubleQuotes: true)));
    alert('safeNewtonsoftPotentialAttendees passed XSS test: ' + safeNewtonsoftPotentialAttendees[0].Name);
</script>
<script>
    var unsafeNewtonsoftPotentialAttendees = @Html.Raw(JsonConvert.SerializeObject(
        new[] { new { Name = "Samuel Jack</script><script>alert('unsafeNewtonsoftPotentialAttendees failed XSS test')</script>" } }));
    alert('unsafeNewtonsoftPotentialAttendees passed XSS test: ' + unsafeNewtonsoftPotentialAttendees[0].Name);
</script>

另见:

答案 2 :(得分:11)

使用Newtonsoft

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