Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store / Retrieve ConnectionString from appSettings.json in ASP.net Core 2 MVC app

I'm looking for the best practice way to store a connection string in appsettings.json in a .net Core 2 MVC app (like you do in web.config in MVC 5).

I want to use Dapper not EF (I found many EF examples).

Something like this:

{
  "ConnectionStrings": {
    "myDatabase": "Server=.;Database=myDatabase;Trusted_Connection=true;"
  },

  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

Surely there are many examples online? Nothing I can find that is for .net core 2.0.

Several things have changed between 1 and 2 and I want to ensure I'm using version 2 best practices.

I've found this - but it seems to be .net core 1: Visual Studio 2017 - MVC Core - Part 05 - Connection String from appsettings.json

This uses key value pair appsettings - not the connectionstrings: Read AppSettings in ASP.NET Core 2.0

Again it's unclear if this is .net Core 1 or 2: Net Core Connection String Dapper visual studio 2017

like image 517
niico Avatar asked May 24 '18 10:05

niico


People also ask

How do I get connectionString in .NET Core?

In ASP.NET Core the configuration system is very flexible, and the connection string could be stored in appsettings. json , an environment variable, the user secret store, or another configuration source. See the Configuration section of the ASP.NET Core documentation for more details.

How can I get the connection string from Appsettings json in .NET Core API?

json file, right click on the Project in Solution Explorer. Then click Add, then New Item and then choose App Settings File option (shown below) and click Add button. Once the File is created, it will have a DefaultConnection, below that a new Connection String entry is added.

How do you read connectionString from configuration file into code behind?

To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].


1 Answers

Just put like shown below in appsettings.json.

"ConnectionStrings": {
    "DefaultConnection": "Data Source=;Initial Catalog=;Persist Security Info=True;User ID=; Password=;"
}

In Startup.cs fetch it as mentioned below:

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }
}

Use dependency injection to inject configuration in controller like mentioned below:

public class MyController : Controller
{
    private readonly IConfiguration _configuration;
    private string connectionString;

    public MyController(IConfiguration configuration) 
    {
        _configuration = configuration;

        connectionString = _configuration.GetConnectionString("DefaultConnection");
    }
}
like image 82
Riddhi Avatar answered Oct 21 '22 00:10

Riddhi