Connection String in ASP.NET Core MVC .NET 8

In this article, you will learn how to manage connection strings and use them in the application.

You will get answers to the following questions:

  • What is a Connection String?
  • How many ways to define and manage connection strings?
  • Sample Codes

What is a Connection String?

The connection string is one kind of text string that is used to establish a connection from the application to the database server database.

The connection string is the collective information of the data source, database name, user name, and password.

How many ways to define and manage connection strings?

Following ways to declare and manage the connection strings:

  1. AppSettings.json
  2. Environment Settings
  3. Static Class

AppSettings.json

Using the AppSettings.json file, you can easily write a connection string.

Define Connection-String

Creating a separate object under the main json object just below Logging.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "MyConnectionString": "Server=xxx.xx.xxx.xx;Database=dbTest;User=xxxxxxx;Password=xx@xx;TrustServerCertificate=True"
  },
  "AllowedHosts": "*"
}

Using Connection-String

Open the HomeController.cs file and update the code.

public class HomeController : Controller
{
    // Inject the IConfiguration interface into your controller to access the connection string from appsettings.json file
    private readonly IConfiguration _configuration;
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
    {
        _logger = logger;
        _configuration = configuration;
    }

    public IActionResult Index()
    {
        // Get the connection string
        string connectionString = _configuration.GetConnectionString("MyConnectionString");
        return View();
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}

Environment Settings

Using the environment setting, it takes more steps to configure the connection string than the appsettings.json file.

Note. You can set environment variables in two ways.

Command Window

setx MyDbConnect "Server=(localdb)\\MSSQLLocalDB;Database=dbMyDb;Trusted_Connection=True;"

Connection-String-AspNet-Core-MVC-Net8

Edit Environment Variable Dialog box.

Connection-String-AspNet-Core-MVC-Net8

Search for “environment” in the start menu.

You can add the new environment variable by clicking the NEW button.

Connection-String-AspNet-Core-MVC-Net8

You can check and update the connection string in Local environment variables

To fetch the local environment variables

string Connt = Environment.GetEnvironmentVariable("MyDbConnect");

Note. You may get null value from above line, you have to restart the Visual Studio because visual studio read Environment Variable at startup only.

Static Class

Create a static class and static property to set the connection string.

public static class DbConnect
{
    public static string DbConnectionString { get; set; } = 
        "Server=xxx.xx.xxx.xx;Database=dbTest;User=xxxxxxx;Password=xx@xx;TrustServerCertificate=True";
}

You can use it in the following way:

string ConStr = DbConnect.DbConnectionString;

Happy Coding.


Recommended Free Ebook
Similar Articles