问题描述: 在Asp.Net Core 3.1中,Appsettings不遵守JsonConverter。当使用自定义的JsonConverter时,Appsettings中的配置值无法正确地转换为目标类型。
解决方法: 要解决这个问题,您可以使用自定义的ConfigurationProvider来解析Appsettings中的配置值,并使用JsonConverter将其转换为目标类型。以下是一个代码示例:
public class DateTimeConverter : JsonConverter
{
public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer)
{
if (reader.Value == null)
return DateTime.MinValue;
if (DateTime.TryParse(reader.Value.ToString(), out DateTime result))
return result;
return DateTime.MinValue;
}
public override void WriteJson(JsonWriter writer, DateTime value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
}
public class CustomConfigurationProvider : ConfigurationProvider
{
private readonly string _jsonFilePath;
public CustomConfigurationProvider(string jsonFilePath)
{
_jsonFilePath = jsonFilePath;
}
public override void Load()
{
var json = File.ReadAllText(_jsonFilePath);
var configValues = JsonConvert.DeserializeObject>(json, new JsonSerializerSettings
{
Converters = new List { new DateTimeConverter() }
});
Data = new Dictionary();
foreach (var entry in configValues)
{
if (entry.Value != null)
{
if (entry.Value is JValue jValue)
{
Data[entry.Key] = jValue.Value.ToString();
}
else
{
Data[entry.Key] = JsonConvert.SerializeObject(entry.Value);
}
}
}
}
}
public void ConfigureServices(IServiceCollection services)
{
// ...
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.Add(new CustomConfigurationSource("appsettings.json"))
.Build();
services.AddSingleton(configuration);
// ...
}
通过以上步骤,您可以使用自定义的JsonConverter来解决Asp.Net Core 3.1中Appsettings不遵守JsonConverter的问题,并正确地将配置值转换为目标类型。