it-swarm.asia

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

我正在尝试使用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?

144
Samuel Jack

你做:

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

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

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

Newtonsoft的JsonConvert.SerializeObjectJson.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>

也可以看看:

39
Jeremy Cook

使用Newtonsoft

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