Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

c# - Access Connection String inside an ASP.NET Core controller

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

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

1 Reply

0 votes
by (71.8m points)

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;
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...