James
James

Reputation: 169

Properties.Settings not available in ASP.NET Core

I am trying to access a connection string stored in Settings.settings within my project. Running Visual Studio 2017 C# ASP.NET Core. The Properties namespace can be accessed, but the only thing it contains is Resources; Settings does not exist there. Every other question related to this I have seen involves Properties being unavailable, but that is not the case here.

Perhaps someone else has run into this issue? Or perhaps this is not where I should be storing a connection string?

Upvotes: 1

Views: 5194

Answers (2)

ctv
ctv

Reputation: 1061

To add to what @Samuel said:

If you're not using EF (perhaps Dapper or something like that), you can access the connection string through the Configuration object:

Your Startup.cs would look something like this:

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

    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        //Register this so it can be injected in you application later.
        services.AddSingleton(Configuration);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        //...
        app.UseMvc();
    }
}

You can then use DI and inject the Configuration object like so:

public class YourClass
{
    IConfigurationRoot _config;
    public YourClass(IConfigurationRoot config)
    {
        _config = config;
    }

    public void SomeMethod()
    {
        var connStr = _config["ConnectionStrings:DefaultConnection"];
    }
}

Take a look at the following link to better understand Configuration in Asp.Net Core: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration

Upvotes: 1

Samuel
Samuel

Reputation: 366

You should read connection string from appsettings.json. Something like the following:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=mydb;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  ...
}

You can then read it in Startup class, see link below (scroll down to ASP.NET Core section of the article).

https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-strings

Upvotes: 1

Related Questions