Home > Blockchain >  Keyvaluepair value issue appsettings
Keyvaluepair value issue appsettings

Time:12-03

This is my appsettings

  {
    "Messages": {
        "ApiUrl": "demo",   
        "ApiKey": {
          "Key": "key",
          "Value": "1234"
        }
    }
  }

Model Class:

public class CPSSettings
{
    public Messages Messages { get; set; } = null!;  
}
public class Messages
{
    public string ApiUrl { get; set; } = null!;
    public KeyValuePair<string?, string?> ApiKey{ get; set; }
} 
       

I am not getting values for _settings.Messages.ApiKey.Key and _settings.Messages.ApiKey.Value

But receiving value for ApiUrl. I have issue with KeyValuePair not receiving a value

public testClient(IOptions<CPSSettings> options)
{  
    _settings = options.Value;
}

//...

if (_settings.Messages.ApiKey.Key is not null 
    && _settings.Messages.ApiKey.Value is not null)
{
    var s = _settings.Messages.ApiKey.Key;    // am getting null vaues in both
    var s1 = _settings.Messages.ApiKey.Value
}

CodePudding user response:

The members of KeyValuePair are readonly. The framework is unable to set those values after initializing the struct

I would suggest you use another object type that you control. One that has modifiable members.

For example

public class CPSSettings {
    public Messages Messages { get; set; } = null!;  
}

public class Messages {
    public string ApiUrl { get; set; } = null!;
    public ApiKey ApiKey{ get; set; } //<-- NOTE THE CHANGE
} 

public class ApiKey {
    public string? Key { get; set; }
    public string? Value { get; set; }
}

That way, when binding the settings, the framework can initialize and properly set the values of the members

CodePudding user response:

Removing CPSSettings would simplify the scenario. See below for how to access configuration values, via Options pattern in .NET, using Messages:

  1. Ensure you have registered Messages within Startup.ConfigureServices(...) (example below).
services.Configure<Messages>(Configuration.GetSection("Messages"));
  1. Receive IOptions<Messages> as testClient constructor parameter (example below).
public testClient(IOptions<Messages> options)
{
    _settings = options.Value;
}

CodePudding user response:

try this

var cpsSettingsSection = configuration.GetSection("Messages");
var cpsSettings = cpsSettingsSection.Get<Messages>();

var url = cpsSettings.ApiUrl;
var key = cpsSettings.ApiKey.Key.Dump();    
var value = cpsSettings.ApiKey.Value.Dump();

//services.Configure<Messages>(cpsSettingsSection);

}

public class Messages
{
    public string ApiUrl { get; set; }
    public KeyValueString ApiKey {get; set;}
 }

public class KeyValueString
{
    public string Key { get; set; }
    public string Value { get; set; }
}
  • Related