In ASP.NET Core, a connection string is a string that contains information about how to connect to a specific data source, such as a database. The connection string usually includes information such as the server name, database name, and credentials (such as a user ID and password) required to connect to the data source.
Connection strings can be stored in various places, but in ASP.NET Core, it’s common to store them in the appsettings.json file. This file is a configuration file that is included with an ASP.NET Core project. It can be used to store various types of application settings, including connection strings.
Connection strings can be accessed in your application code using the Configuration API, which is a built-in feature of ASP.NET Core that allows you to read and manipulate configuration data. The Configuration API provides a way to read the connection string from the appsettings.json file and use it in your code to connect to the data source.
In general, Connection strings are used in the constructor of the DbContext class. The DbContext
class is an important class in the Entity Framework, which is a popular data access technology for ASP.NET Core. The DbContext
class is responsible for interacting with the data source and provides an abstraction over the data source that makes it easier to work with.
You can also encrypt the connection strings in the appsettings.json file to protect sensitive information, such as the user ID and password. The encryption key can be stored in the environment variable for production deployment, or in the user secrets for development.
In ASP.NET Core, connection strings can be stored in the appsettings.json file and accessed using the Configuration API. Here is an example of how to add a connection string in the appsettings.json file
Page Name :- appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": { "MyCon": "Data Source = LAPTOP-PCMAS9LI; Database=CmsShoppingCart; Trusted_Connection=True; MultipleActiveResultSets=True;User ID=sa;Password=123" }
}
add below code on Page Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<CmsShoppingCartContext>(options => options.UseSqlServer
(Configuration.GetConnectionString("MyCon")));
}
If You Facing any Issue Then comment your problem i will help you