简体   繁体   中英

Keyvaluepair value issue appsettings

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
}

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

Removing CPSSettings would simplify the scenario. See below for how to access configuration values, viaOptions 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;
}

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM