HTML标签json序列化,c# – 使用Json.Net序列化模型时自动使用HtmlEncode字符串

本文介绍如何在JSON.NET中实现字符串的HTML转义处理,通过自定义ContractResolver来确保在序列化过程中对字符串属性进行转义,避免XSS攻击。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

您可以使用类似于

Selectively escape HTML in strings during deserialization中的解决方案,并进行一些小的更改:

>更改HtmlEncodingValueProvider以在GetValue而不是SetValue中应用编码(以便它在序列化而不是反序列化时执行编码).

>更改解析程序以将值提供程序应用于所有字符串属性,而不是查找属性.

以下是生成的代码的样子:

public class CustomResolver : DefaultContractResolver

{

protected override IList CreateProperties(Type type, MemberSerialization memberSerialization)

{

IList 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);

}

}

}

像这样使用自定义ContractResolver:

var settings = new JsonSerializerSettings

{

ContractResolver = new CustomResolver(),

Formatting = Formatting.Indented

};

string json = JsonConvert.SerializeObject(your_object, settings);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值