I’m working on an MVC project and can’t seem to retrieve my key and host from the appsetting.json file. I’ve added this code to try and retrieve my api settings from a appsetting.json file in my project. So far the code I have is this.
private readonly ApiSettings _aSettings;
public CardController(IOptions<ApiSettings> aSettings)
{
_aSettings = aSettings.Value;
}
[HttpGet("ApiConfig")]
public ApiSettings Get() => _aSettings;
public IActionResult GetApiSettings()
{
var apiKey = _aSettings.ApiKey;
var apiHost = _aSettings.ApiHost;
return Json(_aSettings);
}
public IActionResult Card(string cardName, string cardNumber)
{
var client = new RestClient($"https://pokemon-tcg-card-prices.p.rapidapi.com/card?cardNumber={cardNumber}&name={cardName}");
var request = new RestRequest();
request.AddHeader("X-RapidAPI-Key", $"{_aSettings.ApiKey}");
request.AddHeader("X-RapidAPI-Host", $"{_aSettings.ApiHost}");
var response = client.Execute(request).Content;
var result = JsonConvert.DeserializeObject<Root>(response);
return View(result);
}
I’ve created a class called ApiSetting to store the variables
public class ApiSettings
{
public string? ApiKey { get; set; }
public string? ApiHost { get; set; }
}
and this is the appsettings.json file
"ApiConfig": {
"ApiKey": "MyApiKey",
"ApiHost": "MyApiHost"
}
and added this to my main program.cs
builder.Services.Configure<ApiSettings>(builder.Configuration.GetSection("ApiConfig"));
I’ve also tried to add this code but it didn’t seem to work either.
public void ConfigureServices(IServiceCollection services)
{
// Load configuration from appsettings.json
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
// Bind the configuration settings to your model
services.Configure<ApiSettings>(configuration.GetSection("ApiSettings"));
// Other configuration...
}
2
Answers
Assuming the
_aSettings
object is not null, here are some suggestions.Directory.GetCurrentDirectory()
resolves to the correct path.appsettings.json
file exists in the path resolved directory path.Hello, I have tried to reproduce, your issue, and seems Its working as expected and I can extract the value from appsettings.json,
I have tried as following way:
Controller:
Class I Used:
Program.cs:
Output:
Note: Please make sure, some other setting has not overriding your value or you haven’t missed anything sharing with us. In addition, please refer to this official document.
However, you could try another alternative to retrieve configuration value by following way:
Class I have Used:
Output:
Note: Please refer to this official document for more information. In addition, you can download this sample for more way.