Home > Enterprise >  Read value from the appsettings config section and inject value in predefined place
Read value from the appsettings config section and inject value in predefined place

Time:10-01

appsettings.json
====    
{
    ...
    "MySettings": {     
        "PublicFeedUrl": "v1/feed?key={feedKey}&location={access_location}",
        "StoragePath":""
    }
}

public class MySettingsModel
{
    public string PublicFeedUrl { get; set; }  
    public string StoragePath { get; set; }  
}

I registered MySettings from the configuration with its class in DI container.

services.Configure<MySettingsModel>(Configuration.GetSection("MySettings")); 

Inside controller I'm injecting IOptions

private readonly IOptions<MySettingsModel> appSettings; 
public MyController(IOptions<MySettingsModel> app)  
{  
    appSettings = app;  
} 

[HttpGet]
public IActionResult Get()
{
    var configFeedUrl = appSettings.PublicFeedUrl;
    var requestMessage = new HttpRequestMessage(HttpMethod.Get, configFeedUrl);
    
    this will make url to be 
    v1/feed?key={feedKey}&location={access_location}
    
    // how can I inject values here to take place on feedKey and access_location    
    var myFeedKey = 123456;
    var myAccessLocation = "Boston";
    
    so that final url looks like this
    var v1/feed?key=123456&location=Boston      
    
    I do not want to change appsettings.json config.
}

CodePudding user response:

Your question has nothing to do with config, it is just a string operation

 var f = appSettings.PublicFeedUrl;
    // "v1/feed?key={feedKey}&location={access_location}";

    var myFeedKey = 123456;
    var myAccessLocation = "Boston";


    var configFeedUrl = f.Replace("{feedKey}",myFeedKey.ToString())
                 .Replace("{access_location}",myAccessLocation);

result

v1/feed?key=123456&location=Boston
  • Related