2016-08-22 139 views
36

我想讀只是從一個配置文件中,因爲這是一個連接字符串名爲「AppAettings.json」將文件添加到我的項目,並添加就可以了這一內容:如何在.NET Core中讀取連接字符串?

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

WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true" 
    }, 
    "Logging": { 
    "IncludeScopes": false, 
    "LogLevel": { 
    "Default": "Debug", 
    "System": "Information", 
    "Microsoft": "Information" 
    } 
} 
} 

在ASP.NET我用這個:

var temp=ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; 

現在我怎麼能讀取C#中的「DefaultConnection」,並將其存儲在.NET核心中的字符串變量?

+0

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration –

回答

26

您可以用GetConnectionString擴展法做到這一點:

string conString = Microsoft 
    .Extensions 
    .Configuration 
    .ConfigurationExtensions 
    .GetConnectionString(this.Configuration, "DefaultConnection"); 

System.Console.WriteLine(conString); 

或結構類對於DI:

public class SmtpConfig 
{ 
    public string Server { get; set; } 
    public string User { get; set; } 
    public string Pass { get; set; } 
    public int Port { get; set; } 
} 

啓動:

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")); 

然後在家裏控制器:

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

與這appsettings.json:

"ConnectionStrings": { 
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true" 
}, 

"Smtp": { 
    "Server": "0.0.0.1", 
    "User": "[email protected]", 
    "Pass": "123456789", 
    "Port": "25" 
    } 
+1

'Configure'是擴展方法。應該最常用的是這樣的:'services.Configure (Configuration.GetSection(「SMTP」));'當然,這是同樣的事情,但我認爲人們不知道會剛開始做「錯」的方式,使用未註釋的行,所以也許最好刪除行。 ;) –

+0

@詹姆斯威爾金斯:非常有效的擔憂。不過,其實我更喜歡這個符號在使用它作爲擴展方法 - 這樣,我知道正在做什麼,在哪裏,並能複製粘貼從1處到另一處,沒有得到由於缺少進口的命名空間的問題。唯一的問題是,MS使用名稱空間進行分類,而不是使用名稱衝突防護 - 因此,名稱空間太長。另外,如果您刪除namspaces並使用擴展方法,那麼相同類型的人將開始抱怨代碼沒有編譯。不是每個人都使用IDE,所以這種方式更好。 –

+0

我發現大多數人都不會刻意去把「usings」在他們的代碼示例,這是您點的情況下,也是爲什麼擴展方法失敗的另一點。 ;) –

1

,我找到了解決這個是使用的方式在Startup的構建器中添加JsonFile(允許它找到存儲在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(); 
    } 

然後我可以設置配置字符串如下:

var connectionString = _config.GetConnectionString("DbContextSettings:ConnectionString"); 

這是DOTNET核心1.1

+4

如何在我的控件中訪問_config? – sunny

+0

將它添加到Startup.cs的ConfigureServices中的DI容器中。 –

26

張貼的答案是好的,但並沒有直接回答同樣的問題,我對讀取連接字符串。通過大量搜索,我找到了一個更簡單的方法。

In Startup。CS

public void ConfigureServices(IServiceCollection services) 
{ 
    ... 
    // Add the whole configuration object here. 
    services.AddSingleton<IConfiguration>(Configuration); 
} 

在您的控制器構造函數在視圖中添加代碼的配置和現場參數爲它吧

private readonly IConfiguration configuration; 

public HomeController(IConfiguration config) 
{ 
    configuration = config; 
} 

後,你可以訪問它想:

connectionString = configuration.GetConnectionString("DefaultConnection"); 
1

查看鏈接瞭解更多信息: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings

JSON

{ 
     "ConnectionStrings": { 
     "BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;" 
     }, 
    } 

C#Startup.cs

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddDbContext<BloggingContext>(options => 
     options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase"))); 
}