8

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.

1

3 Answers 3

12

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/

Sign up to request clarification or add additional context in comments.

Comments

8

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

-1

--I use Solution
string condb = "";
public readonly IConfiguration _configuration;
public ValuesController(IConfiguration configuration)
{
_configuration = configuration;
condb = _configuration[ConnectionStrings:DefaultConnection];
}

2 Comments

Please also explain what the posted code does and why it will resolve the question.
"ConnectionStrings": { "DefaultConnection": "Server=localhost;Database=YourAppDb;User Id=yourUsername;Password=yourPassword;Trusted_Connection=false;MultipleActiveResultSets=true;", }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.