Where is the equivalent of HttpUtility.JavaScriptStringEncode in .Net Core 1.1?
I have found myself in need of scrubbing javascript out of comments being added by users in a .Net Core MVC application. In previous frameworks, this could be achieved by first passing your string into JavaScriptStringEncode.
var comment = HttpUtility.JavaScriptStringEncode(model.Comment);
However, I haven’t been able to find the equivalent in .net core.
Here is an equivalent of HttpUtility.JavaScriptStringEncode
in .net core:
using System.Text.Encodings.Web; //part of System.Text.Encodings.Web nuget package
...
var encodedText = JavaScriptEncoder.Default.Encode("TextToEncode");
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);
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 });
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)
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.
You can use the same method, use it like this example on razor:
@System.Web.HttpUtility.JavaScriptStringEncode(YourStringHere)
UPDATE:
As @Dai said, this will only work if you’re targeting .NET Framework, which is descouraged with ASP.NET Core.