Is there a way to configure Json.Net to automatically encode all strings like HtmlEncode(myString)
when the model is serialized?
HtmlEncode is a convenient way to access the HttpUtility. HtmlEncode method at run time from an ASP.NET application. Internally, HtmlEncode uses HttpUtility. HtmlEncode to encode strings. To encode or decode values outside of a web application, use the WebUtility class.
Specifies the settings on a JsonSerializer object. Newtonsoft.Json.
So if you are intending to write JSON into the html as part of Javascript (a very common use), you need to encode JSON contents to HTML unfortunately. It's much better to avoid this and download data separately. those are some very good points!
Try this:
var json = JObject.Parse("{'Name':'<script>alert(1);</script>'}");
var serializerSettings = new JsonSerializerSettings()
{
StringEscapeHandling = StringEscapeHandling.EscapeHtml
};
var result = JsonConvert.SerializeObject(json, serializerSettings);
result will be:
{"Name":"\u003cscript\u003ealert(1);\u003c/script\u003e"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With