【发布时间】:2018-05-11 15:51:02
【问题描述】:
我正在使用 C# 和 .NET Framework 4.7 开发 ASP.NET Core 2.0.2 Web API。
我想在方法的控制器中从appsettings.json 获取连接字符串。
我是在 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")));
[ ... ]
}
但我不知道如何在控制器中执行此操作。我找到了这个教程,Configure an ASP.NET Core App,但它使用一个类来访问配置的选项,public class MyOptions
我尝试过像Startup.cs、Configuration.GetConnectionString("MyContext") 那样做,但它无法识别Configuration 类。
我的问题是: 如何在控制器中获取连接字符串?
【问题讨论】:
-
在此处查看“使用选项和配置对象”部分 docs.microsoft.com/en-us/aspnet/core/fundamentals/… 在 IOptions 上使用 DI
-
配置["subsection:connStr"]
标签: c# asp.net-core configuration