157

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

<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?

4

3 回答 3

196

你做:

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

在 Beta 2 之前的版本中,您可以这样做:

@(new HtmlString(Json.Encode(Model.PotentialAttendees)))
于 2010-11-01T20:27:18.993 回答
46

Newtonsoft 的JsonConvert.SerializeObject行为与Json.Encode@david-k-egghead 建议的行为不同,并且会导致您面临 XSS 攻击

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

<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>

也可以看看:

于 2014-04-17T21:17:06.327 回答
12

使用牛顿软件

<script type="text/jscript">
  var potentialAttendees  = @(Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.PotentialAttendees)))
</script>
于 2013-09-16T15:22:00.733 回答