Мое ограничение состоит в том, что мне нужно использовать System.text.json!
Это то, что я попробовал. < /P>
Код: Выделить всё
[AttributeUsage(AttributeTargets.Property)]
public class SensitiveDataAttribute : JsonAttribute
{
}
public class LoginModel
{
public string? Email { get; set; }
[SensitiveData]
public string? Password { get; set; }
public override string ToString() => this.ToLogJsonString();
}
public class SensitiveDataConverter : JsonConverter
{
public SensitiveDataConverter()
{
}
public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return reader.GetString();
}
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{
var attribute = value.GetType().GetTypeInfo().GetCustomAttribute();
if (attribute is null)
{
writer.WriteStringValue(value);
return;
}
var secret = new String(value.Select(x => '*').ToArray());
writer.WriteStringValue(secret);
}
}
public static class LoggableObjectExtensions
{
public static string ToLogJsonString(this object value)
{
JsonSerializerOptions options = new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
PropertyNameCaseInsensitive = true,
WriteIndented = false,
};
options.Converters.Add(new SensitiveDataConverter());
return JsonSerializer.Serialize(value, options);
}
}
< /code>
В конце хотел увидеть результат < /p>
var model = new LoginModel
{
Email = "test@test.com",
Password = "Abrakadabra"
};
Console.WriteLine(model.ToLogJsonString());
< /code>
Проблема в том, что мой атрибут не был распознан в Sensividividataconverter. Есть идеи? Хотя я не хочу конфиденциальных данных, зарегистрированных в консоли, я хочу сериализовать их при других обстоятельствах, поэтому добавление [jsonignore] Подробнее здесь: https://stackoverflow.com/questions/722 ... n-using-sy
Мобильная версия