Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
141 views
Welcome To Ask or Share your Answers For Others

1 Answer

You may directly inject IConfiguration configuration into your controller (it is registered in DI container by default) :

// using Microsoft.Extensions.Configuration;

public class YourController : Controller
{
      public YourController (IConfiguration configuration)
      {
           var connString = Configuration.GetConnectionString("MyContext");
      }

}

But anyway consider using the IOptions pattern as it will be more flexible.

public class MyOptions
{
    public string ConnString { get; set; }
}

public void ConfigureServices(IServiceCollection services)
{ 
    // Adds services required for using options.
    services.AddOptions();

    services.Configure<MyOptions>(myOptions =>
    {
        myOptions.ConnString = Configuration.GetConnectionString("MyContext");
    });

    ...
}

then

  public YourController ((IOptions<MyOptions> optionsAccessor)
  {
      var connString = optionsAccessor.Value.ConnString;
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...