Access Connection String inside an ASP.NET Core controller

Viewed 10024

I'm developing an ASP.NET Core 2.0.2 Web API with C# and .NET Framework 4.7.

I want to get the connection string from appsettings.json in a method's controller.

I did it in Startup.cs:

using Microsoft.Extensions.Configuration;

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

    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)
    {
        services.AddMvc();
        services.AddDbContext<MyContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("MyContext")));

        [ ... ]
}

But I don't know how to do it in a controller. I have found this tutorial, Configure an ASP.NET Core App, but it uses a class to access configuration's options, public class MyOptions

I have tried to do it like in Startup.cs, Configuration.GetConnectionString("MyContext"), but it doesn't recognize Configuration class.

My question is: How can I get the connection string in a controller?

4 Answers
Related