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.
To define the connection strings in appsettings. json it is important to specify it in the right section of the JSON structure. Now we can read it in our code by calling the GetConnectionString method in the Microsoft. Extensions.
Right-click on your connection and select "Properties". You will get the Properties window for your connection. Find the "Connection String" property and select the "connection string". So now your connection string is in your hands; you can use it anywhere you want.
The posted answer is fine but didn't directly answer the same question I had about reading in a connection string. Through much searching I found a slightly simpler way of doing this.
In Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
// Add the whole configuration object here.
services.AddSingleton<IConfiguration>(Configuration);
}
In your controller add a field for the configuration and a parameter for it on a constructor
private readonly IConfiguration configuration;
public HomeController(IConfiguration config)
{
configuration = config;
}
Now later in your view code you can access it like:
connectionString = configuration.GetConnectionString("DefaultConnection");
You can do this with the GetConnectionString extension-method:
string conString = Microsoft
.Extensions
.Configuration
.ConfigurationExtensions
.GetConnectionString(this.Configuration, "DefaultConnection");
System.Console.WriteLine(conString);
or with a structured-class for DI:
public class SmtpConfig
{
public string Server { get; set; }
public string User { get; set; }
public string Pass { get; set; }
public int Port { get; set; }
}
Startup:
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// http://developer.telerik.com/featured/new-configuration-model-asp-net-core/
// services.Configure<SmtpConfig>(Configuration.GetSection("Smtp"));
Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions.Configure<SmtpConfig>(services, Configuration.GetSection("Smtp"));
And then in the home-controller:
public class HomeController : Controller
{
public SmtpConfig SmtpConfig { get; }
public HomeController(Microsoft.Extensions.Options.IOptions<SmtpConfig> smtpConfig)
{
SmtpConfig = smtpConfig.Value;
} //Action Controller
public IActionResult Index()
{
System.Console.WriteLine(SmtpConfig);
return View();
}
with this in appsettings.json:
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Smtp": {
"Server": "0.0.0.1",
"User": "[email protected]",
"Pass": "123456789",
"Port": "25"
}
See link for more info: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings
JSON
{
"ConnectionStrings": {
"BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
},
}
C# Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BloggingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
}
EDIT: aspnetcore, starting 3.1: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1
The way that I found to resolve this was to use AddJsonFile in a builder at Startup (which allows it to find the configuration stored in the appsettings.json file) and then use that to set a private _config variable
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)
.AddEnvironmentVariables();
_config = builder.Build();
}
And then I could set the configuration string as follows:
var connectionString = _config.GetConnectionString("DbContextSettings:ConnectionString");
This is on dotnet core 1.1
This is how I did it:
I added the connection string at appsettings.json
"ConnectionStrings": {
"conStr": "Server=MYSERVER;Database=MYDB;Trusted_Connection=True;MultipleActiveResultSets=true"},
I created a class called SqlHelper
public class SqlHelper
{
//this field gets initialized at Startup.cs
public static string conStr;
public static SqlConnection GetConnection()
{
try
{
SqlConnection connection = new SqlConnection(conStr);
return connection;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
At the Startup.cs I used ConfigurationExtensions.GetConnectionString to get the connection,and I assigned it to SqlHelper.conStr
public Startup(IConfiguration configuration)
{
Configuration = configuration;
SqlHelper.connectionString = ConfigurationExtensions.GetConnectionString(this.Configuration, "conStr");
}
Now wherever you need the connection string you just call it like this:
SqlHelper.GetConnection();
ASP.NET Core (in my case 3.1) provides us with Constructor injections into Controllers, so you may simply add following constructor:
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
private readonly IConfiguration m_config;
public TestController(IConfiguration config)
{
m_config = config;
}
[HttpGet]
public string Get()
{
//you can get connection string as follows
string connectionString = m_config.GetConnectionString("Default")
}
}
Here what appsettings.json may look like:
{
"ConnectionStrings": {
"Default": "YOUR_CONNECTION_STRING"
}
}
There is another approach. In my example you see some business logic in repository class that I use with dependency injection in ASP .NET MVC Core 3.1.
And here I want to get connectiongString
for that business logic because probably another repository will have access to another database at all.
This pattern allows you in the same business logic repository have access to different databases.
C#
public interface IStatsRepository
{
IEnumerable<FederalDistrict> FederalDistricts();
}
class StatsRepository : IStatsRepository
{
private readonly DbContextOptionsBuilder<EFCoreTestContext>
optionsBuilder = new DbContextOptionsBuilder<EFCoreTestContext>();
private readonly IConfigurationRoot configurationRoot;
public StatsRepository()
{
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
configurationRoot = configurationBuilder.Build();
}
public IEnumerable<FederalDistrict> FederalDistricts()
{
var conn = configurationRoot.GetConnectionString("EFCoreTestContext");
optionsBuilder.UseSqlServer(conn);
using (var ctx = new EFCoreTestContext(optionsBuilder.Options))
{
return ctx.FederalDistricts.Include(x => x.FederalSubjects).ToList();
}
}
}
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"EFCoreTestContext": "Data Source=DESKTOP-GNJKL2V\\MSSQLSERVER2014;Database=Test;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With