How to Read Connection String in .Net Core

How to read connection string in .NET Core?

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": "user@company.com",
"Pass": "123456789",
"Port": "25"
}

how to read connection string using configuration in .NET CORE 3.1

There are few things to be noted,

Have you injected in the constructor?

public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

and use it as

 public void ConfigureServices(IServiceCollection services)
{
var connection = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<ShelterPZ_DBContext>(options => options.UseSqlServer(connection));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}

How to read connection string in ASP .NET Core Razor Pages

You can create an AppSettings class like this, by copying your appsettings.json to QuickType:

public class AppSettings
{
public static ConnectionStrings ConnectionStrings { get; set; }
public static Logging Logging { get; set; }
public static string AllowedHosts { get; set; }
}

public class ConnectionStrings
{
public string CustomerDb { get; set; }
public string SupplierDb { get; set; }
}

public class Logging
{
public LogLevel LogLevel { get; set; }
}

public class LogLevel
{
public string Default { get; set; }
public string Microsoft { get; set; }
public string MicrosoftHostingLifetime { get; set; }
}

Then in Startup:

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
Configuration.Get<AppSettings>();
services.AddControllersWithViews();
}

I use static for easy access instead of injecting AppSettings through DI.

Or if you don't want to put them all in a class, check out the Options pattern from Microsoft.

Config connection string in .net core 6

.Net 6 Simplifies a lot of a tasks and introduces WebApplicationBuilder which in turn gives you access to the new Configuration builder and Service Collection

var builder = WebApplication.CreateBuilder(args);

Properties

  • Configuration : A collection of configuration providers for the application to compose. This is useful for adding new configuration sources and providers.

  • Environment : Provides information about the web hosting environment an application is running.

  • Host : An IHostBuilder for configuring host specific properties, but not building. To build after configuration, call Build().

  • Logging : A collection of logging providers for the application to compose. This is useful for adding new logging providers.

  • Services : A collection of services for the application to compose. This is useful for adding user provided or framework provided services.

  • WebHost : An IWebHostBuilder for configuring server specific properties, but not building. To build after configuration, call Build().

To add a DbContext to the Di Container and configure it, there are many options however the most straightforward is

builder.Services.AddDbContext<SomeDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});

Nugets packages

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.SqlServer to use UseSqlServer

How to read connection string from appsettings.json in a DBContext file in Asp.Net Core?

You can setup your db context in the startup file and not override OnConfiguring at all.
Just add a constructor that takes DbContextOptions<TContext> to your DbContext class. This constructor should pass on the parameter to the base class' constructor,
then call AddDbContext<TContext> in your Startup.Configure as follows:

// your TestContext showing constructor
public class TestContext : DbContext
{
public TestContext(DbContextOptions<TestContext> options) : base(options){ }
}

// Then in Startup.cs
public class Startup
{
public IConfiguration Configuration {get;}

public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TeamsDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("connection_string")));
}
}

Worth noting is that the AddDbContext<TContext> method has overloads that allow setting the service lifetime for the context to Singleton or Transient if you so wish. The default is Scoped.

Get ConnectionString value from app.settings.json file in asp.net core 3.1

There is no issue in my code.

There is issue in appsetitngs.json file. According to me it is not an issue.
I just change the connection string order and make it to up and after it i am getting the connection string value in application.

Below is the place where i changed the order:

{
"ConnectionStrings": {
"ConnectionString1": "data source=192.xxx.x.xxx; database=MyDatabase; user id=myuser; password=myuser; Pooling=false; Connection Lifetime=10000;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}

How to get ConnectionString from Secrets.json in Asp.Net Core 6?

Before ASP.NET 6:

You can adding additional Secrets.json file to configuration argument in Startup.cs like below:

public class Startup
{
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
configuration = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
.AddJsonFile("Secrets.json")
.Build();

Configuration = configuration;
}

public IConfiguration Configuration { get; }
//...
}

Or add it in Program.cs:

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;

config.SetBasePath(env.ContentRootPath)
.AddJsonFile("Secrets.json", optional: true, reloadOnChange: true);

})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});

In ASP.NET 6:

You can add it in Program.cs like below:

var builder = WebApplication.CreateBuilder(args);
builder.Configuration
.SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("Secrets.json");

builder.Services.AddDbContext<POTS.myDBContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("myConxStr")));

// Add services to the container....
var app = builder.Build();
//....

Then be sure your json file(Secrets.json) must be like below:

{
"ConnectionStrings": {
"myConxStr": "xxxxxxx"
}
}

.NET Core Database The Connection String property has not been initialized

You create the SqlConnection without providing any connection string.
Pass the connection string to the SqlConnection constructor
using (SqlConnection conn = new SqlConnection(connectionString ))

ConnectionString in .NET Core 6

Problem is how you start your Web API from the service. You are using Process without setting ProcessStartInfo.WorkingDirectory to the folder containing exe and configuration and the started process shares the working directory with parent one, so either move appsettings.json to the parent project folder or set the WorkingDirectory to match the directory containing the exe:

toDoTest.StartInfo.UseShellExecute = false;
toDoTest.StartInfo.WorkingDirectory = "C:\\Develop\\ToDoMVCtutorial\\bin\\Release\\net6.0\\publish\\";

Also you can try redirecting your Web API output to capture the logs.



Related Topics



Leave a reply



Submit