mot*_*deh 87 c# connection-string asp.net-core-1.0
我想从配置文件中只读取一个连接字符串,并为此添加一个名为"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中的字符串变量中?
Bra*_*ton 89
发布的答案很好,但没有直接回答我在连接字符串中读取的相同问题.通过大量搜索,我发现了一种稍微简单的方法.
在Startup.cs中
public void ConfigureServices(IServiceCollection services)
{
...
// Add the whole configuration object here.
services.AddSingleton<IConfiguration>(Configuration);
}
Run Code Online (Sandbox Code Playgroud)
在控制器中,在构造函数中为配置添加一个字段并为其添加一个参数
private readonly IConfiguration configuration;
public HomeController(IConfiguration config)
{
configuration = config;
}
Run Code Online (Sandbox Code Playgroud)
现在稍后在您的视图代码中,您可以访问它:
connectionString = configuration.GetConnectionString("DefaultConnection");
Run Code Online (Sandbox Code Playgroud)
Ste*_*ger 78
您可以使用GetConnectionString扩展方法执行此操作:
string conString = Microsoft
.Extensions
.Configuration
.ConfigurationExtensions
.GetConnectionString(this.Configuration, "DefaultConnection");
System.Console.WriteLine(conString);
Run Code Online (Sandbox Code Playgroud)
或者使用DI的结构化类:
public class SmtpConfig
{
public string Server { get; set; }
public string User { get; set; }
public string Pass { get; set; }
public int Port { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
启动:
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// http://developer.telerik.com/featured/new-configuration-model-asp-net-core/
// services.Configure<SmtpConfig>(Configuration.GetSection("Smtp"));
Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions.Configure<SmtpConfig>(services, Configuration.GetSection("Smtp"));
Run Code Online (Sandbox Code Playgroud)
然后在家庭控制器:
public class HomeController : Controller
{
public SmtpConfig SmtpConfig { get; }
public HomeController(Microsoft.Extensions.Options.IOptions<SmtpConfig> smtpConfig)
{
SmtpConfig = smtpConfig.Value;
} //Action Controller
public IActionResult Index()
{
System.Console.WriteLine(SmtpConfig);
return View();
}
Run Code Online (Sandbox Code Playgroud)
在appsettings.json中使用它:
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Smtp": {
"Server": "0.0.0.1",
"User": "user@company.com",
"Pass": "123456789",
"Port": "25"
}
Run Code Online (Sandbox Code Playgroud)
小智 25
在 .NET Core 6 中
应用程序设置.json
"ConnectionStrings": {
"DefaultConnection": "Server=**Server Name**;Database=**DB NAME**;Trusted_Connection=True;MultipleActiveResultSets=true"
}
Run Code Online (Sandbox Code Playgroud)
程序.cs
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));
Run Code Online (Sandbox Code Playgroud)
数据库上下文
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
}
Run Code Online (Sandbox Code Playgroud)
小智 14
我就是这样做的:
我在 appsettings.json 添加了连接字符串
"ConnectionStrings": {
"conStr": "Server=MYSERVER;Database=MYDB;Trusted_Connection=True;MultipleActiveResultSets=true"},
Run Code Online (Sandbox Code Playgroud)
我创建了一个名为 SqlHelper 的类
public class SqlHelper
{
//this field gets initialized at Startup.cs
public static string conStr;
public static SqlConnection GetConnection()
{
try
{
SqlConnection connection = new SqlConnection(conStr);
return connection;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在 Startup.cs 中,我使用 ConfigurationExtensions.GetConnectionString 来获取连接,并将其分配给 SqlHelper.conStr
public Startup(IConfiguration configuration)
{
Configuration = configuration;
SqlHelper.connectionString = ConfigurationExtensions.GetConnectionString(this.Configuration, "conStr");
}
Run Code Online (Sandbox Code Playgroud)
现在,无论您需要连接字符串,您都可以这样调用它:
SqlHelper.GetConnection();
Run Code Online (Sandbox Code Playgroud)
mar*_*ate 13
有关详细信息,请参阅链接:https: //docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings
JSON
{
"ConnectionStrings": {
"BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
},
}
Run Code Online (Sandbox Code Playgroud)
C#Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BloggingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
}
Run Code Online (Sandbox Code Playgroud)
我发现解决此问题的方法是在启动时在构建器中使用AddJsonFile(这使它可以找到存储在appsettings.json文件中的配置),然后使用它来设置私有_config变量
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
_config = builder.Build();
}
Run Code Online (Sandbox Code Playgroud)
然后我可以将配置字符串设置如下:
var connectionString = _config.GetConnectionString("DbContextSettings:ConnectionString");
Run Code Online (Sandbox Code Playgroud)
这是在dotnet core 1.1上
小智 5
ASP.NET Core(在我的例子中是3.1)为我们提供了到 Controllers 的构造函数注入,所以你可以简单地添加以下构造函数:
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
private readonly IConfiguration m_config;
public TestController(IConfiguration config)
{
m_config = config;
}
[HttpGet]
public string Get()
{
//you can get connection string as follows
string connectionString = m_config.GetConnectionString("Default")
}
}
Run Code Online (Sandbox Code Playgroud)
appsettings.json 可能如下所示:
{
"ConnectionStrings": {
"Default": "YOUR_CONNECTION_STRING"
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
126808 次 |
最近记录: |