如何使用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 = [{"Name":"Samuel Jack"},];</script>如何让Razor发出未编码的JSON?
3 回答
慕婉清6462132
TA贡献1804条经验 获得超2个赞
你做:
@Html.Raw(Json.Encode(Model.PotentialAttendees))
在早于Beta 2的版本中,您可以这样做:
@(new HtmlString(Json.Encode(Model.PotentialAttendees)))
尚方宝剑之说
TA贡献1788条经验 获得超4个赞
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>
哈士奇WWW
TA贡献1799条经验 获得超6个赞
使用Newtonsoft
<script type="text/jscript"> var potentialAttendees = @(Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.PotentialAttendees)))</script>
- 3 回答
- 0 关注
- 569 浏览
添加回答
举报
0/150
提交
取消