Mat*_*t R 16 javascript asp.net-core-mvc
我发现自己需要从.Net Core MVC应用程序中的用户添加的注释中清除javascript.在以前的框架中,这可以通过首先将您的字符串传递给JavaScriptStringEncode来实现.
var comment = HttpUtility.JavaScriptStringEncode(model.Comment);
Run Code Online (Sandbox Code Playgroud)
但是,我还没能找到.net核心中的等价物.
Rav*_*Dev 13
这是HttpUtility.JavaScriptStringEncode.net核心的等价物:
using System.Text.Encodings.Web; //part of System.Text.Encodings.Web nuget package
...
var encodedText = JavaScriptEncoder.Default.Encode("TextToEncode");
Run Code Online (Sandbox Code Playgroud)
There is a helper available as @Json.Serialize in the views. That uses JSON.Net, taking into account any formatting options configured in Startup.cs:
var foo = @Json.Serialize(model);
Run Code Online (Sandbox Code Playgroud)
Bear in mind this does not XSS-sanitizes the json by default! However you can use an overload that lets you do that, specifying the StringEscapeHandling option of JSON.Net as EscapeHtml:
@using Newtonsoft.Json
...
var foo = @Json.Serialize(model, new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeHtml });
Run Code Online (Sandbox Code Playgroud)
You can maybe wrap that into your own helper like @Json.SafeSerialize or @SafeJson.Serialize.
I haven't found a better way than your own helpers without forcing the default JsonOutputFormatter to behave this way through the json options in Startup:
services.AddMvc().AddJsonOptions(opts => opts.SerializerSettings.StringEscapeHandling = StringEscapeHandling.EscapeHtml)
Run Code Online (Sandbox Code Playgroud)
The problem with the latter approach (and why you might prefer the custom helper) is that it would also affect the JSONs returned from your APIs.
PS. I have raised this on github.
| 归档时间: |
|
| 查看次数: |
2950 次 |
| 最近记录: |