appsettings with special characters in .NET Core

后端 未结 2 1045
灰色年华
灰色年华 2021-01-04 02:11

I have a small .NET Core console app which has an appsettings.json file containing different configuration sections and some of the values contain accents (for

2条回答
  •  悲哀的现实
    2021-01-04 02:51

    Inspired by Deep Dive into Microsoft Configuration, I found a solution. My solution is to combine the use of json and xml.

    In Your Program.cs, You need to add the load of xml. Example where I map settings to a POCO:

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration(AddDbConfiguration)
                .UseStartup();
    
        private static void AddDbConfiguration(WebHostBuilderContext context, IConfigurationBuilder builder)
        {
            var configuration = builder.Build();
            builder.AddXmlFile("appsettings.xml");
        }
    

    My xml file:

    
    
      
        Specialskolekørsel
        1
        True
        
    
    

    My ConfigureServices:

    public void ConfigureServices(IServiceCollection services)
    {
       services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
       services.Configure(Configuration.GetSection(nameof(ConfigSettings)));
    }
    

    My Controller:

    public HomeController(IOptions config)
    {
        Database = config.Value.Database;
    }
    

    Now the danish letter ø shows as expected. I hope You will find this useful.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题