简体   繁体   English

JavaScript因查询字符串中的特殊字符而崩溃

[英]Javascript crashes on special characters from query string

To use this value in my TypeScript I am getting it from my query string like this: 要在TypeScript使用此值,请从查询字符串中获取该值,如下所示:

var UserName = @Request.QueryString["UserName"];

But I get a Unexpeted Identifier error on it because if in DevTool if I go to where it breaks that query string has a value like this: 但是我收到了一个Unexpeted Identifier error ,因为如果在DevTool如果我转到中断的地方,则查询字符串的值是这样的:

var UserName = ANT -- ANT 37690 / THIRD PARTY var UserName = ANT-ANT 37690 /第三方

So is there a way to do some kind of sanitation on it so it wouldn't crash? 那么,有没有办法对它进行某种卫生处理,以免崩溃? I guess there are illegal characters in that value for JS ? 我猜JS值中有非法字符吗?

The error has nothing to do with "special" characters, but with the fact that the right side of the assignment - unwrapped in quotes - contains what js engine views as unknown identifier[s]. 该错误与“特殊”字符无关,而是与赋值的右侧(用引号引起来的)包含js引擎视为未知标识符的事实有关。

One way to properly format data that becomes part of javascript code is to use JavaScriptSerializer class from System.Web.Script.Serialization namespace. 正确格式化成为javascript代码一部分的数据的一种方法是使用System.Web.Script.Serialization命名空间中的JavaScriptSerializer类。

var UserName = @new System.Web.Script.Serialization.JavaScriptSerializer().Seria‌​lize(Request.Query‌​St‌​ring["UserName"]);

The shorter version of this for a string is: 字符串的缩写形式是:

var UserName = "@System.Web.HttpUtility.JavaScriptStringEncode(Request.Query‌​St‌​ring["UserName"])";

or overloaded version that wraps the result in double quotes: 或将结果用双引号引起来的重载版本:

var UserName = @System.Web.HttpUtility.JavaScriptStringEncode(Request.Query‌​St‌​ring["UserName"], true);

You need to include quotes for the value. 您需要在值中包含引号。

var UserName = "@(Request.QueryString["UserName"])";

Otherwise the name will come through verbatim in your code and cause the problems you are seeing. 否则,该名称将逐字出现在您的代码中,并引起您所看到的问题。

There is no need to protect against an attack vector here as the user can alter the page as they see fit at any time with a user script, and the QueryString is entered by them and only seen as a result by them in this scenario. 此处无需采取防御措施,因为用户可以随时使用用户脚本来更改页面,因为他们可以使用他们认为合适的页面,并且他们输入QueryString并在这种情况下仅将其视为结果。

If there was a need to scrub the user input, it should be done prior to it actually reaching the view on server side. 如果需要清理用户输入,则应在实际到达服务器端视图之前进行。 However, if still concerned about scrubbing output into a view in this type of scenario in general, it would be prudent to include an encode from razor's library. 但是,如果通常仍然担心在这种情况下将输出清理到视图中,则最好包含来自razor库的编码。

var sanitizedJsVariable = "@System.Web.HttpUtility.JavaScriptStringEncode(model.VariableFromServer)";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM