Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

appsettings with special characters in .NET Core

Tags:

c#

.net-core

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 example á or ó).

When I parse a given configuration section I get weird chars back for those.

Is there an option in the configuration namespace that could help in parsing the string correctly?

Real example:

{
  "Loc": "https://www.mywebsite.com/image.jpg",
  "Caption": "Ocasión - Los mejores vehículos"
},
like image 402
Carlos Torrecillas Avatar asked Mar 06 '19 15:03

Carlos Torrecillas


2 Answers

JSON mandates UTF-8 as the file encoding. Your file is most likely saved in some other encoding, possibly Codepage 1252. Make sure you save the file as UTF-8 and your characters will work.

Different tools handle this differently.

For Notepad there's an Encoding selection in the Save dialog:

enter image description here

Visual Studio has a Save with Encoding option in the Save dialog:

enter image description here

You could also write a small program or script to do the conversion, e.g. the following PowerShell pipeline:

(Get-Content appsettings.json) | Set-Content -Encoding Utf8 appsettings.json
like image 101
Joey Avatar answered Nov 15 '22 22:11

Joey


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<Startup>();

    private static void AddDbConfiguration(WebHostBuilderContext context, IConfigurationBuilder builder)
    {
        var configuration = builder.Build();
        builder.AddXmlFile("appsettings.xml");
    }

My xml file:

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <ConfigSettings>
    <Database>Specialskolekørsel</Database>
    <SystemId>1</SystemId>
    <EnableAudit>True</EnableAudit>
    </ConfigSettings>
</root>

My ConfigureServices:

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

My Controller:

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

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

like image 3
bromose Avatar answered Nov 15 '22 21:11

bromose