在 asp.net core 3.1 中,使用新的 System.Text.Json,我尝试在 appsettings 部分使用自定义 JsonConverter。手动序列化/反序列化尊重转换器就好了,但通过选项模式从 appSettings 读取则不然。这是我所拥有的:
Json转换器。为简单起见,这只是将字符串值转换为大写:
public class UpperConverter : JsonConverter<string>
{
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
reader.GetString().ToUpper();
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) =>
writer.WriteStringValue(value == null ? "" : value.ToUpper());
}
Run Code Online (Sandbox Code Playgroud)
appsettings 类,在字符串属性上声明转换器:
public class MyOptions
{
public const string Name = "MyOptions";
[JsonConverter(typeof(UpperConverter))]
public string MyString { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Startup.cs 更改以准备所有内容:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews()
.AddJsonOptions(options =>
{ …Run Code Online (Sandbox Code Playgroud) c# application-settings .net-core asp.net-core jsonconverter