如何连接code在ASP.NET MVC 3的Razor视图嵌入的JavaScript? [英] How to encode embedded javascript in Razor view in ASP.NET MVC 3?
问题描述
我如何正确地连接在下列情况下code JavaScript的:
How do I properly encode JavaScript in the following context:
<html>
...
<script type="text/javascript">
var settings = @Html.PleaseEncode(settings.ToJson());
// ...
</script>
</html>
在我的JSON对象的值由应用程序管理员设置的,所以我认为他们需要正确连接codeD - 既为HTML和JavaScript
The values in my JSON objects are set by the application administrator, so I assume they need properly encoded -- both for HTML and JavaScript.
我使用 System.Web.Script.Serialization.JavaScriptSerializer 做的JSON编码。
它看起来像的JavaScriptSerializer做了一些编码,它输出文本&LT;无&GT;
为 \\ u003cNone \\ u003c
,但我不敢肯定它是多么安全。现在,我使用 @ Html.Raw
,因为它的作品给予安全投入。它生成以下内容:
I'm using System.Web.Script.Serialization.JavaScriptSerializer to do the JSON encoding.
It looks like JavaScriptSerializer does some encoding as it outputs the text <None>
as \u003cNone\u003c
, but I'm not sure how safe it is. Right now, I'm using @Html.Raw
as it works given safe input. It generates the following:
var settings = {"UnselectedReason":"None Selected", /*...*/};
如果我用 @ Html.En code
然后我得到:
var settings = {&quot;UnselectedReason&quot;:&quot;None Selected&quot;, /*...*/};
我试过与无 AntiXSS ,但我看不出有什么区别两种方式。
I've tried with and without AntiXSS but I see no difference either way.
推荐答案
AntiXSS有JavaScriptEn code,但它是专为单个项目,而不是采取的,呃,设置了一整套。
AntiXSS has JavaScriptEncode, but it's designed for individual items, rather than taking a whole set of, err, settings.
所以,如果你传递{UnselectedReason:无选择,/.../}它会吃的报价和其他东西,这可能不是你想要的。相反,我会做什么是你的toJSON我会建立设置了一个字符串生成器,像
So if you passed in {"UnselectedReason":"None Selected", /.../} it'd eat the quotes and other things, which is probably not what you want. Instead what I'd do is in your ToJson I'd build the settings up with a string builder, something like
StringBuilder sb = new StringBuilder();
sb.Append("{");
foreach(KeyValuePair kv in mySettings)
{
sb.Append("\"");
sb.Append(Microsoft.Security.Application.Encoder.JavaScriptEncode(kv.Key, true);
sb.Append(":");
sb.Append(Microsoft.Security.Application.Encoder.JavaScriptEncode(kv.Value, true);
sb.Append("\",");
}
string outputString = sb.ToString().TrimEnd(",") + "}";
return new HtmlString(outputString);
的注:code是把我的头顶部,并没有被连输入到VS.它说明了校长和可能不能编译!的
这篇关于如何连接code在ASP.NET MVC 3的Razor视图嵌入的JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!