我正在尝试从我的 appsettings.json 文件中导入 System.Type
作为设置对象的一部分。对象的其余部分导入正常,但是当我将 System.Type
属性添加到我的设置对象时,出现以下异常:
An exception of type 'System.InvalidOperationException' occurred in Microsoft.Extensions.Configuration.Binder.dll but was not handled in user code
Additional information: Failed to convert 'MyType' to type 'System.Type'.
我的 appsettings.json 类似于:
"Settings": {
"Url": "some url",
"Type: "MyType"
}
我的设置对象看起来像:
public class Settings
{
public string Url {get; set;}
public Type Type {get; set;}
}
我的 Startup.cs 包含使用它来绑定(bind)设置:
var foo = Configuration.GetSection("Settings").Get<Settings>(); // This is where the exception occurs.
显然,Configuration Binder 正在将 MyType
作为字符串读取,并且不知道如何将其转换为 System.Type
。是否可以在 Binder 级别这样做,或者我是否需要做一些反射(reflection)以将该字符串转换为 System.Type
在它被使用的地方?
最佳答案
现在是可能的。
使用以下 NuGet 包在 .net core 3.1 上测试:
- Microsoft.Extensions.Configuration 5.0.0
- Microsoft.Extensions.Configuration.Binder 5.0.0
- Microsoft.Extensions.Configuration.Json 5.0.0
在对配置进行任何操作之前,必须在应用程序启动时注册 StringToTypeConverter。
应用设置.json:
{
"Settings": {
"Url": "some URL",
"Type": "System.String, mscorlib" /*Fully qualified type name*/
}
}
代码:
class Program
{
static void Main()
{
// Registration of StringToTypeConverter
TypeDescriptor.AddAttributes(typeof(Type), new TypeConverterAttribute(typeof(StringToTypeConverter)));
// Build configuration
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false)
.Build();
var settings = configuration.GetSection("Settings").Get<Settings>();
Console.WriteLine("Settings.Type: {0}", settings.Type);
}
public class Settings
{
public string Url { get; set; }
public Type Type { get; set; }
}
internal class StringToTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string stringValue)
{
return Type.GetType(stringValue);
}
return base.ConvertFrom(context, culture, value);
}
}
}
关于c# - 是否可以从 .net 核心应用程序中的 appsettings.json 文件导入 System.Type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41370836/