相关疑难解决方法(0)

如何在.NET Core中读取连接字符串?

我想从配置文件中只读取一个连接字符串,并为此添加一个名为"appsettings.json"的文件到我的项目中,并在其上添加以下内容:

{
"ConnectionStrings": {
  "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-

 WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
    "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Debug",
    "System": "Information",
    "Microsoft": "Information"
   }
 }
}
Run Code Online (Sandbox Code Playgroud)

在ASP.NET上我使用了这个:

 var temp=ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
Run Code Online (Sandbox Code Playgroud)

现在我如何在C#中读取"DefaultConnection"并将其存储在.NET Core中的字符串变量中?

c# connection-string asp.net-core-1.0

87
推荐指数
7
解决办法
13万
查看次数

从appsettings.json获取ConnectionString,而不是在.NET Core 2.0 App中进行硬编码

我在NET Core2.0 App中有以下类.

// required when local database does not exist or was deleted
public class ToDoContextFactory : IDesignTimeDbContextFactory<AppContext>
{
    public AppContext CreateDbContext(string[] args)
    {
        var builder = new DbContextOptionsBuilder<AppContext>();
        builder.UseSqlServer("Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true");
        return new AppContext(builder.Options);
    }
}
Run Code Online (Sandbox Code Playgroud)

当Database不存在时,在Core 2.0中需要进行迁移,并且必须在运行update-database时创建.
升级到ASP.NET Core 2.0后无法创建迁移

我想在2个地方(这里和appsettings.json)没有ConnectionString,但只在.json,所以我试图更换

"Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true"
Run Code Online (Sandbox Code Playgroud)

同

ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString
Run Code Online (Sandbox Code Playgroud)

但它不起作用,我得到空值.

更新1:
请注意,在Core 2中明确添加.json是不必要的,所以问题不在于文件.
https://andrewlock.net/exploring-program-and-startup-in-asp-net-core-2-preview1-2/

更新2:
此外,我已经使用Configuration从.json向Context发送ConnectionString:

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

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<AppContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); …
Run Code Online (Sandbox Code Playgroud)

connection-string appsettings asp.net-core

43
推荐指数
6
解决办法
10万
查看次数

如何在类库项目中获取连接字符串

在我的 .net 解决方案中,我有两个不同的项目:一个 MVC 核心 Web 应用程序项目和一个类库项目。在 Web 应用程序项目中,数据库连接字符串在appsettings.json文件中。我想从类库项目访问该连接字符串。是否可以?如果是,如何?如果有更好的方法来获取连接字符串,请告诉我。

c# asp.net-mvc connection-string entity-framework-6

5
推荐指数
1
解决办法
5876
查看次数