Automatically HtmlEncode strings when model is serialized with Json.Net
2 answers
You can use a solution similar to the solution to selectively remove HTML in lines during deserialization , with a few minor changes:
- Change
HtmlEncodingValueProvider
to apply encoding inGetValue
, notSetValue
(so that it encodes serialization, not deserialization). - Modify the transformer to apply the value provider to all row properties, rather than look up the attribute.
This is what the resulting code would look like:
public class CustomResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
// Attach an HtmlEncodingValueProvider instance to all string properties
foreach (JsonProperty prop in props.Where(p => p.PropertyType == typeof(string)))
{
PropertyInfo pi = type.GetProperty(prop.UnderlyingName);
if (pi != null)
{
prop.ValueProvider = new HtmlEncodingValueProvider(pi);
}
}
return props;
}
protected class HtmlEncodingValueProvider : IValueProvider
{
PropertyInfo targetProperty;
public HtmlEncodingValueProvider(PropertyInfo targetProperty)
{
this.targetProperty = targetProperty;
}
// SetValue gets called by Json.Net during deserialization.
// The value parameter has the original value read from the JSON;
// target is the object on which to set the value.
public void SetValue(object target, object value)
{
targetProperty.SetValue(target, (string)value);
}
// GetValue is called by Json.Net during serialization.
// The target parameter has the object from which to read the string;
// the return value is the string that gets written to the JSON
public object GetValue(object target)
{
string value = (string)targetProperty.GetValue(target);
return System.Web.HttpUtility.HtmlEncode(value);
}
}
}
Use custom ContractResolver
like this:
var settings = new JsonSerializerSettings
{
ContractResolver = new CustomResolver(),
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(your_object, settings);
Fiddle: https://dotnetfiddle.net/RhFlk8
+2
source to share
Try the following:
var json = JObject.Parse("{'Name':'<script>alert(1);</script>'}");
var serializerSettings = new JsonSerializerSettings()
{
StringEscapeHandling = StringEscapeHandling.EscapeHtml
};
var result = JsonConvert.SerializeObject(json, serializerSettings);
The result
will be:
{"Name":"\u003cscript\u003ealert(1);\u003c/script\u003e"}
+1
source to share