using System.Text; using System.Text.Json; using System.Text.Json.Serialization; namespace YLErp.Web.App { /// /// /// public class AntiXssConverter : JsonConverter { public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetString(); } public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) { if (value != null) { var needEscape = false; foreach (var ch in value) { if (ch == '<' || ch == '>') { needEscape = true; break; } } if (needEscape) { var sb = new StringBuilder(value.Length + 30); foreach (var c in value) { if (c == '<') { sb.Append("<"); } else if (c == '>') { sb.Append(">"); } else if (c == '&') { sb.Append("&"); } else { sb.Append(c); } } value = sb.ToString(); } } writer.WriteStringValue(value); } } }