Asp.net core ASP.NET Core 2.x OnConfiguring get connectionstring from appsettings.json
刚刚开始使用ASP.NET内核,到目前为止,它给人留下了深刻的印象。在生成的代码中,(请参见下文)。我想更改硬编码的连接字符串,以便从Asp.net core ASP.NET Core 2.x OnConfiguring get connectionstring from appsettings.json,asp.net-core,visual-studio-2017,Asp.net Core,Visual Studio 2017,刚刚开始使用ASP.NET内核,到目前为止,它给人留下了深刻的印象。在生成的代码中,(请参见下文)。我想更改硬编码的连接字符串,以便从appsettings.json文件中获取它 这显然是不可能的。我还没有找到一个有效的示例(甚至没有构建) 发生什么事了?? 请帮忙 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.
appsettings.json
文件中获取它
这显然是不可能的。我还没有找到一个有效的示例(甚至没有构建)
发生什么事了??
请帮忙
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Server=xxxxxxx;Database=xxxxx;Trusted_Connection=True;");
}
}
提供的链接解决了一个方面的问题,但在onconfigurang
中不起作用。我做错了什么
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.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
var connection = Configuration.GetConnectionString("ConnectionName");
services.AddDbContext<SurveyContext>(options => options.UseSqlServer(connection));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
配置(选项=>
{
//此lambda确定给定请求是否需要非必要cookie的用户同意。
options.checkApprovered=context=>true;
options.MinimumSameSitePolicy=SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
var connection=Configuration.GetConnectionString(“ConnectionName”);
services.AddDbContext(options=>options.UseSqlServer(connection));
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{controller=Home}/{action=Index}/{id?}”);
});
}
}
在要访问appsettings.json的位置
JToken jAppSettings = JToken.Parse(
File.ReadAllText(Path.Combine(Environment.CurrentDirectory,
"appsettings.json")));
现在既然您有了对象,就可以访问它的内容了。
让我知道它是否有效。当您使用
Scaffold DbContext
时,默认情况下,它会将字符串硬编码到DbContext类中(因此它是开箱即用的)。您需要在启动类中注册DbContext
,才能继续。要设置此设置,您可以在中查看说明
请注意,Configuration
属性直接连接到appsettings.json和其他几个位置。您可以在中阅读更多关于它的信息。虽然您始终可以使用appsettings.json文件,但通常建议将您的安全机密保存在源代码之外的外部json文件中。在开发过程中解决此问题的最佳解决方案是使用。最简单的使用方法是在VisualStudio上右键单击您的项目并选择“管理用户机密”。这将打开一个已经连接到配置
对象的json文件
设置好后,您需要使用依赖项注入来访问db上下文
public class HomeController : Controller
{
public HomeController(SurveyContext context)
{
// you can set the context you get here as a property or field
// you can use visual studio's shortcut ctrl + . when the cursor is on "context"
// you can then use the context variable inside your actions
}
}
使用using时,每次都会创建一个新连接。使用注入可以确保每个请求只创建一个连接,而不管它被使用了多少次。在.NET核心项目的启动类中,您通常在ConfigureServices函数中注册它
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<YourContext>(options => options.UseSqlServer(connection));
}
public void配置服务(IServiceCollection服务)
{
services.AddDbContext(options=>options.UseSqlServer(connection));
}
当您在.NET内核的启动类中时,从appsettings.json读取值是没有问题的
您可以在Microsoft上阅读更多内容,即:此函数是否在您的数据库上下文中?你到底生成了什么代码?您可以提供您所采取的步骤吗?请检查此Nope not my code,它是由VS2017在package manager窗口中使用
Scaffold DbContext
命令生成的。当您使用Scaffold DbContext
选项时,您应该在DbContext
类的顶部获得一个文档url。你检查过了吗?为了让读者更清楚,请更新你的问题,说你在代码生成中使用了Scaffold DbContext
。如果这是他想要做的,我建议改为使用IConfiguration。它已经是一个json格式的字符串@NevilleNazerane no,这没有帮助either@Minu这是迄今为止我发现的最接近的一次,至少在布朗斯的书中是这样。我只是需要一种强有力的方法来表达内容:)关于.NETCore,最棘手的一点是,在使用它之前,你需要理解一系列的概念。这个答案可能“有效”,但我认为这不是正确的解决方案。正如@NevilleNazerane所说,您需要使用i配置
。您必须确保正确生成它,并且使用连接字符串的正确路径。是的,根据文档,您也尝试过。StartUp.cs
中的代码甚至没有被触碰。没有被触碰吗?如何使用您的DbContext
?在使用语句中,就像我多年来使用EFusing(var context=new SurveyContext())
一样,一旦启动设置完成,您需要使用数据库上下文,而不使用依赖项注入。再次检查该链接,我将更新我的答案,说明您需要如何使用db上下文我在您的答案中没有看到您在控制器中使用DI获取数据,而不是使用语句,甚至都不知道there@djack109你能告诉我你的startup类是什么样子的吗?在哪里调用startup类?从那以后,我相信我可以帮助你添加到我的原始帖子中。我查看了你的启动代码,但没有立即发现任何问题。但到底发生了什么事,你会加入公司吗