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

我试图写一个对象作为JSON到我的Asp.Net MVC视图使用Razor,如下所示:

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

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

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

我如何让剃刀发出未经编码的JSON?

你做:

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

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

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

Newtonsoft的JsonConvert.SerializeObjectJson.Encode行为并不一样,并且按照@ david-k-egghead的build议,可以打开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> 

也可以看看:

  • JsonConvert.SerializeObject的输出是否需要在Razor视图中编码?
  • XSS预防规则

使用Newtonsoft

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