Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically HtmlEncode strings when the model is serialized with Json.Net

Is there a way to configure Json.Net to automatically encode all strings like HtmlEncode(myString) when the model is serialized?

like image 720
Buda Gavril Avatar asked May 22 '17 14:05

Buda Gavril


People also ask

What is HtmlEncode asp net?

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.

What is Jsonserializersettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json.

Should JSON be HTML encoded?

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!


1 Answers

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"}
like image 104
Mohammad Nikravan Avatar answered Sep 22 '22 06:09

Mohammad Nikravan