skip to Main Content

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


  1. Assuming the _aSettings object is not null, here are some suggestions.

    1. Check Directory.GetCurrentDirectory() resolves to the correct path.
    2. Check the appsettings.json file exists in the path resolved directory path.
    Login or Signup to reply.
  2. I’m working on an MVC project and can’t seem to retrieve my key and
    host from the appsetting.json file.

    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:

    public class TestCardController : Controller
        {
            private readonly ApiSettings _aSettings;
    
            public TestCardController(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);
            }
        }
    

    Class I Used:

    public class ApiSettings
        {
            public string? ApiKey { get; set; }
            public string? ApiHost { get; set; }
    
        }
    

    Program.cs:

    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.Configure<ApiSettings>(builder.Configuration.GetSection("ApiConfig"));
    

    Output:

    enter image description here

    enter image description here

    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:

    public class CardController : Controller
        {
    
            private readonly IConfiguration _appSettingsValue;
            private string _apiKey;
            private string _apiHost;
    
            public CardController(IConfiguration configuration)
            {
              
                _appSettingsValue = configuration;
                _apiKey = _appSettingsValue["ApiConfig:ApiKey"]!;
                _apiHost = _appSettingsValue["ApiConfig:ApiHost"]!;
            }
    
            
    
            public IActionResult GetApiSettings()
            {
                var configValues = new ConfigValue();
                configValues.ApiKey = _apiKey;
                configValues.ApiHost = _apiHost;
    
                return Json(configValues);
            }
        }
    

    Class I have Used:

    public class ConfigValue
        {
            public string? ApiKey { get; set;}
            public string? ApiHost { get; set;}
        }
    

    Output:

    enter image description here

    Note: Please refer to this official document for more information. In addition, you can download this sample for more way.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search