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

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

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


德玛西亚99
浏览 570回答 3
3回答

慕婉清6462132

你做:@Html.Raw(Json.Encode(Model.PotentialAttendees))在早于Beta 2的版本中,您可以这样做:@(new&nbsp;HtmlString(Json.Encode(Model.PotentialAttendees)))

尚方宝剑之说

Newtonsoft的JsonConvert.SerializeObject表现与Json.Encode@ david-k-egghead建议的行为不同,并且可以让你接受XSS攻击。将此代码放入Razor视图中以查看使用Json.Encode是否安全,并且可以在JavaScript上下文中使Newtonsoft安全,但不是没有额外的工作。<script> &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;jsonEncodePotentialAttendees&nbsp;=&nbsp;@Html.Raw(Json.Encode( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new[]&nbsp;{&nbsp;new&nbsp;{&nbsp;Name&nbsp;=&nbsp;"Samuel&nbsp;Jack</script><script>alert('jsonEncodePotentialAttendees&nbsp;failed&nbsp;XSS&nbsp;test')</script>"&nbsp;}&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;)); &nbsp;&nbsp;&nbsp;&nbsp;alert('jsonEncodePotentialAttendees&nbsp;passed&nbsp;XSS&nbsp;test:&nbsp;'&nbsp;+&nbsp;jsonEncodePotentialAttendees[0].Name);</script><script> &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;safeNewtonsoftPotentialAttendees&nbsp;=&nbsp;JSON.parse(@Html.Raw(HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new[]&nbsp;{&nbsp;new&nbsp;{&nbsp;Name&nbsp;=&nbsp;"Samuel&nbsp;Jack</script><script>alert('safeNewtonsoftPotentialAttendees&nbsp;failed&nbsp;XSS&nbsp;test')</script>"&nbsp;}&nbsp;}),&nbsp;addDoubleQuotes:&nbsp;true))); &nbsp;&nbsp;&nbsp;&nbsp;alert('safeNewtonsoftPotentialAttendees&nbsp;passed&nbsp;XSS&nbsp;test:&nbsp;'&nbsp;+&nbsp;safeNewtonsoftPotentialAttendees[0].Name);</script><script> &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;unsafeNewtonsoftPotentialAttendees&nbsp;=&nbsp;@Html.Raw(JsonConvert.SerializeObject( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new[]&nbsp;{&nbsp;new&nbsp;{&nbsp;Name&nbsp;=&nbsp;"Samuel&nbsp;Jack</script><script>alert('unsafeNewtonsoftPotentialAttendees&nbsp;failed&nbsp;XSS&nbsp;test')</script>"&nbsp;}&nbsp;})); &nbsp;&nbsp;&nbsp;&nbsp;alert('unsafeNewtonsoftPotentialAttendees&nbsp;passed&nbsp;XSS&nbsp;test:&nbsp;'&nbsp;+&nbsp;unsafeNewtonsoftPotentialAttendees[0].Name);</script>

哈士奇WWW

使用Newtonsoft<script&nbsp;type="text/jscript"> &nbsp;&nbsp;var&nbsp;potentialAttendees&nbsp;&nbsp;=&nbsp;@(Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.PotentialAttendees)))</script>
打开App,查看更多内容
随时随地看视频慕课网APP