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

Viewed 13101

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

3 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"}

I found a very simple way doing this (WebAPI2).

When you set your object properties, just encode it with below.

myObject.encoded_field = HttpUtility.HtmlEncode(your_html_content)

Related