The easiest and cleanest way to get configurations values in .NET is through the IOptions interface.
Add the following lines of code to your Program.cs
builder.Services .AddOptions<OpenAISettings>() .BindConfiguration("OpenAI");
Next create a class called OpenAISettings.
public class OpenAISettings { public string Url { get; set; } = string.Empty; public string api_key { get; set; } = string.Empty; }
In your AppSettings.json add the OpenAI section.
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "OpenAI": { "Url" : "https://openai.com/chat" "api_key" : "XXXXXXXXXXXXXXXXXX" } }
That’s it. Now you have access to your configuration settings via the Dependency Injection container. In your controller inject the IOptions interface like this.
public HomeController(IOptions<OpenAISettings> opt) { }