I want to create the database connection in my .net core Web API how to I write the connection string. In App setting file how to I write the connection string.
3 Answers
I got my answer
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-ConfigurationSample-ad90971f-6620-4bc1-ad28-650c59478cc1;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
here is link http://aspnetmonsters.com/2016/01/json-config-in-aspnetcoremvc/
Comments
WEB API has a configuration file 'appsettings.json', in this file you can put all the configuration or variables that you need, for example would be like this:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
//->
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Initial Catalog=dbname;MultipleActiveResultSets=true;User ID=sa;Password=mypass"
},
"Jwt": {
"SecretKey": "myjwtpass"
},
"EmailConfiguration": {
"SmtpServer": "mysmtpserver",
"SmtpPort": 2525,
"SmtpUsername": "myusername",
"SmtpPassword": "mypassword"
}
//<-
}
To obtain the values of the configuration we show the following example:
In the constructor get this from injection:
public IConfiguration Configuration { get; }
public MyClassName(IConfiguration configuration)
{
Configuration = configuration;
}
In some method:
public void SomeMethod()
{
var jwtPass = Configuration["Jwt:SecretKey"];
var connStr = Configuration["ConnectionStrings:DefaultConnection"];
}
Comments
--I use Solution
string condb = "";
public readonly IConfiguration _configuration;
public ValuesController(IConfiguration configuration)
{
_configuration = configuration;
condb = _configuration[ConnectionStrings:DefaultConnection];
}