Search code examples
c#asp.net-coreconfigurationblazorasp.net-core-configuration

How to read AWS RegionEndpoint from appsettings.json?


Blazor Server. I have a model

public class S3SvcConfiguration: IS3SvcConfiguration
{
    public string AccessKey { get; set; }
    public string SecretKey { get; set; }
    public RegionEndpoint RegionPoint { get; set; }
    public string S3Url { get; set; }
}

But when I read the appsettings.json configuration the RegionEndpoint is null: The RegionEndpoint is AWS type.

"S3SvcConfiguration": {
    "RegionPoint": "us-east-2",
    "S3Url": "http://myhost:9000",
    "AccessKey": "qwerty",
    "SecretKey": "qwerty123"
  },

I read it

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddSingleton<IS3SvcConfiguration>(Configuration.GetSection("S3SvcConfiguration").Get<S3SvcConfiguration>());
    services.AddScoped <IS3FileSvc,S3FileSvc> ();
}

ALl values populated but RegionPoint is null. How to read appsettings.json configuration to populate the RegionPoint value?


Solution

  • RegionEndpoint is part of their custom configuration but you try to populate it from a simple string when they would have had code to handle that.

    Consider changing the approach to manually convert that string to the desired value

    public void ConfigureServices(IServiceCollection services) {
        services.AddRazorPages();
        services.AddServerSideBlazor();
    
        S3SvcConfiguration config = Configuration.GetSection("S3SvcConfiguration").Get<S3SvcConfiguration>();
        string region = Configuration.GetValue<string>("S3SvcConfiguration:RegionPoint");
        config.RegionPoint = RegionEndpoint.GetBySystemName(region);
        services.AddSingleton<IS3SvcConfiguration>(config);
    
        services.AddScoped <IS3FileSvc,S3FileSvc> ();
    }