使用Json.NET

JsonConvert.SerializeObject(new { Property = "<script>alert('o hai');</script>" })

returns

{"Property":"<script>alert('o hai');</script>"}

Is it possible for the value to be escaped by SerializeObject to prevent a hostile script from executing? I'd prefer not to make changes to the object itself.

编辑:理想情况下,我希望将清理集成到SerializeObject调用中,而不必在SerializeObject之前或之后处理该对象.

编辑:JsonConvert.SerializeObject中的字符串输出被赋给脚本挡路中的一个全局变量,我相信这就是xss问题所在.

推荐答案

Functionality to achieve this was added in version 4.5.11

This allows you to add various type of escaping to the output.

This is my LinqPad test:

    var settings = new JsonSerializerSettings();

    settings.StringEscapeHandling = StringEscapeHandling.EscapeHtml;

    var output = JsonConvert.SerializeObject(new { Property = "<script>alert('o hai');</script>" }, settings);

    Debug.Print(output);

输出

{"Property":"\u003cscript\u003ealert(\u0027o hai\u0027);\u003c/script\u003e"}

Just as a disclaimer, this isn't a golden bullet to fix xss, but should help you mitigate it a bit given your example.

Json相关问答推荐

如何在Gatsby/Reaction中获取JSON-File子 node

在PowerShell中,如何获取数据对所在的JSON对象的名称

PowerShell脚本未按预期生成预期的JSON输出

在Golang中从 struct 手动创建JSON对象

解析SQL中的嵌套JSON

数据到jsonObject到数据到 struct 是可能的吗?

用 Jolt 替换 JSON 中的值

震动范围改善

(已回答)JSON 读取函数返回未定义而不是预期值 - Typescript

Delphi 11.3无法从变体创建/添加JSON

Golang gin接收json数据和图片

如何使用 serde_json 构建有状态的流式解析器?

错误字符串的长度超过了maxJsonLength属性设置的值

将 js Array() 转换为 JSON 对象以用于 JQuery .ajax

json.dumps 打乱了顺序

如何在 django rest 框架中定义列表字段?

数据包含连续问号时无法理解的 jQuery $.ajax() 行为

区分字符串和列表的 Pythonic 方式是什么?

严重:找不到媒体类型 = 应用程序/json、类型 = 类 com.jersey.jaxb.Todo、通用类型 = 类 com.jersey.jaxb.Todo 的 MessageBodyWriter

Gson 将一组数据对象转换为 json - Android