Where do I store site login information with ASP.NET Core 7 MVC?

jp2code 21 Reputation points
2023-07-06T20:34:03.9133333+00:00

In older ASP.NET WebForms, I could store and retrieve any data I needed in the Web.config file.

Now in ASP.NET Core 7, I see how to get the database connection string using the appsettings.json file, but it only appears to be accessible from Program.cs before the application starts.

Maybe I am missing something.

I have an API that has assigned me a Client ID and a Client Secret. I could hard code those into the class, but that is very poor programming.

How are we developers supposed to store and retrieve these now?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,738 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,566 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,841 Reputation points Microsoft Vendor
    2023-07-12T06:55:34.2766667+00:00

    Hi @jp2code

    In older ASP.NET WebForms, I could store and retrieve any data I needed in the Web.config file. Now in ASP.NET Core 7, I see how to get the database connection string using the appsettings.json file, but it only appears to be accessible from Program.cs before the application starts.

    As we all known, in the older WebForms application, the configuration setting is stored in the Web.config file. To read the configuration setting, we need to use the System.Configuration Assembly to read XML configuration files such as the Web.config file. And then, use the ConfigurationManager.GetSection() method or ConfigurationManager.AppSettings to get the configuration setting.

    In asp.net core application, it supports many methods of configuration. In ASP.NET Core application, the configuration is stored in name-value pairs, and it can be read at runtime from various parts of the application. The application configuration data may come from

    • File, such as JSON, XML, INI
    • Environment variables
    • Command Line arguments
    • An in-memory collection
    • Custom providers

    Generally, the configuration setting is stored in the appsetting.json file, like this:

    User's image

    Then, to access the value, we need to use Microsoft.Extensions.Configuration extension and the IConfiguration interface (this interface provides the related method to get the configuration value).

    In Program.cs file, the code like this, this is similar like you did in the WebForms appplication: to get the data via ConfigurationManager.

    User's image

    Then, in the Controller, since the application configuration is used with dependency injection, we don't need to register it in the program.cs file or use the new key word to create an IConfiguration instance, we can directly use the constructor injection method to use it, and the DI container will help to create the instance.

    User's image

    More detail information about the configuration, see Configuration in ASP.NET Core.

    I have an API that has assigned me a Client ID and a Client Secret.

    Do you mean the client id and client secret is belong to personal? If that is the case, appsettings.json file might not a good choice. You can store the personal data into database or use Azure Key Vault. Generally, the appsettings.json file could use to store the public configuration value for the application, everyone can access it.

    Besides, about the use of dependency injection, the official documentation already explains it clearly.

    For example, we have the following Interface and Class:

        public interface IDateTime
        {
            DateTime GetCurrentDate();
        }
        public class SystemDateTime : IDateTime
        {
            public DateTime GetCurrentDate ()
            {
                 return DateTime.Now;
            }
        }
    

    In the older WebForm application, to call the GetCurrentDate method, we have to use the new key word to create the class instance, then call the GetCurrentDate method.

    But in the Asp.net core. using dependency injection, we can do it as below:

    register the service in the program.cs file: then the DI container will create the instance based on the service lifetime.

    builder.Services.AddScoped<IDateTime, SystemDateTime>();
    

    In the controller, inject the IDateTime, without using the new key word, after that we can call the related method.

    User's image

    More information, see:

    Overview of dependency injection

    .NET dependency injection

    Dependency injection into controllers in ASP.NET Core

    Getting Started with Dependency Injection in ASP.NET Core using C#


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion


2 additional answers

Sort by: Most helpful
  1. AgaveJoe 29,281 Reputation points
    2023-07-06T20:44:29.3733333+00:00

    Now in ASP.NET Core 7, I see how to get the database connection string using the appsettings.json file, but it only appears to be accessible from Program.cs before the application starts.

    Configuration is accessible using ASP.NET Core dependency injection.

    Dependency injection in ASP.NET Core

    appsetting.json

    {
      "ConnectionStrings": {
        "DefaultConnection": "Data Source=ApplicationDbContext.db"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*"
    }
    
    

    Constructor injection

        public class IndexModel : PageModel
        {
            private readonly ILogger<IndexModel> _logger;
            private readonly IConfiguration _configuration;
            public IndexModel(ILogger<IndexModel> logger, IConfiguration configuration)
            {
                _logger = logger;
                _configuration = configuration;
            }
    
            public void OnGet()
            {
                connectionString = _configuration["ConnectionStrings:DefaultConnection"];
            }
    
            public string connectionString { get; set; }
        }
    

    How are we developers supposed to store and retrieve these now?

    ASP.NET has several options for storing configuration. I think you'll be interested in reading the official documentation and pick a configuration approach that best fits your needs.

    Configuration in ASP.NET Core


  2. Bruce (SqlWork.com) 69,501 Reputation points
    2023-07-07T17:45:53.0366667+00:00

    also you can read the setting into poco object and add as services, so your code is not tied to any configuration service.

    also it common inject a dbconnection, so again the code does not need access to the connection strings.

      public class IndexModel : PageModel
        {
            private readonly ILogger<IndexModel> _logger;
            private readonly DBContext _db;
            public IndexModel(ILogger<IndexModel> logger, DBContext db)
            {
                _logger = logger;
                _db = db;
            }
    
            public async Task OnGet()
            {
                var result = await _db.....;
    
            }
    
        }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.