c# - 属性的自定义配置绑定(bind)器

标签 c# asp.net-core asp.net-core-1.1

我在 ASP.NET Core 1.1 解决方案中使用配置绑定(bind)。基本上,我在“ConfigureServices Startup”部分中有一些用于绑定(bind)的简单代码,如下所示:

services.AddSingleton(Configuration.GetSection("SettingsSection").Get<SettingsClass>());

问题在于我的类作为 int 属性,通常绑定(bind)到配置文件中的 int 值,但也可以绑定(bind)到字符串“disabled”。在幕后,如果该属性绑定(bind)到字符串“disabled”,我希望该属性获得值 -1。

它可能比这更复杂,但为了简洁起见,我进行了简化。

我的问题是这样的:我如何提供一个自定义绑定(bind)器/转换器来覆盖SettingsClass中特定属性的配置绑定(bind),以便在进行字符串转换时它将“disabled”转换为-1,而不是抛出“disabled”无法转换为 Int32 的异常?

最佳答案

看来,由于 ConfigurationBinder 使用类型的 TypeDescriptor 来获取转换器,因此我要做的唯一方法就是实现自定义类型转换器并将其插入到类 I' 的 TypeDescriptor 中m 转换为(在本例中为 Int32)。

因此,基本上,在配置发生之前添加此内容:

TypeDescriptor.AddAttributes(typeof(int), new TypeConverterAttribute(typeof(MyCustomIntConverter)));

MyCustomIntConverter 看起来像这样:

public class MyCustomIntConverter  : Int32Converter
{
    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        if (value != null && value is string)
        {
            string stringValue = value as string;
            if(stringValue == "disabled")
            {
                return -1;
            }
        }
        return base.ConvertFrom(context, culture, value);
    }
}

似乎有点矫枉过正,因为现在应用程序中任何地方的 Int32“禁用”都将始终转换为 -1。如果有人知道一种侵入性较小的方法来做到这一点,请告诉我。

关于c# - 属性的自定义配置绑定(bind)器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42007114/

相关文章:

c# - LINQ 项目总和集合以返回带有结果的对象(多列)

c# - 如何测试 apiController

c# - asp.net core 2.0 部署 - InvalidOperationException : The antiforgery token could not be decrypted

visual-studio - 托管调试助手 'FatalExecutionEngineError' 0xc0000005

c# - .NET Core 中的环境变量配置

c# - Entity Framework 、批量插入和维护关系

c# - 从麦克风捕获音频而不回放

c# - 在使用 MapWhen 进行分支时注册中间件,以便仅为一组端点运行它

.net - 安装2.0后,项目属性的 “Target framework”下拉列表中缺少.NETCoreApp 2.0选项

database - 如何在 ASP.NET Core 中使用 DbConfiguration 类