![](/img/trans.png)
[英]Read ConnectionString from Application Settings in Web.config
[英]FluentNHibernate cannot read connectionString from web.config
當我使用 FluentNHibernate 時,它無法從 web.config 讀取連接字符串。 我正在使用 ASP.NET Core Web 應用程序 (.NET Framework)、Fluent NHibernate 2.0.3 和 NHibernate 4.0.0.4000。
注釋的方式可以很好地訪問數據庫,而未注釋的方式則不起作用。
return Fluently.Configure()
//.Database(MySQLConfiguration.Standard.ConnectionString("Server=localhost;Port=3307; Uid=root; Pwd=usbw;Database=hellonhibernate"))
.Database(MySQLConfiguration.Standard.ConnectionString(c => c.FromConnectionStringWithKey("TRP123456")))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<PersonMap>())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<SessionMap>())
.ExposeConfiguration(CreateSchema)
.BuildSessionFactory();
web.config 是
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
</system.webServer>
<connectionStrings>
<add name="TRP123456" connectionString="server=localhost;port=3307;uid=root;password=admin;database=hellonhibernate;" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
</configuration>
這是我得到的錯誤。 請幫忙看看有什么問題。 謝謝你。
項目結構如下
首先檢查這個問題我認為它可能會解決您的問題Access WebConfig in DotNet Core
另一種解決方案是改用 appsettings.json 文件。
您可以通過將 json 文件添加到您的項目來做到這一點。 與 project.json 文件相同的文件夾。
在您的 startup.cs 中,您只需將您的文件映射到您的應用程序配置,如下所示:
public static IConfigurationRoot Configuration = null;
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) // in my case the file name is appsettings.json
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build(); // returns IConfigurationRoot that can be used to access your settings later
}
現在我不確定我在那里創建的靜態變量它可能不是最好的方法。 但它給了我我需要的東西。
然后您可以使用它來獲取您的連接字符串:
Startup.Configuration["AppSettings:ConnectionString"]
鑒於您的 appsettings.json 文件中有一個 ConnectionString 鍵。
{
"AppSettings":
{
"ConnectionString": "" //type your connection string in here
}
}
更好的是添加一個 AppSettings 類,如下所示:
public class AppSettings
{
public string ConnectionString { get; set; }
}
現在您需要將其映射為服務(將其添加到您的中間件)。
public void ConfigureServices(IServiceCollection services)
{
//other services
services.Configure<AppSettings> Configuration.GetSection("AppSettings"));
//other services
}
所以你可以將它注入你的控制器:
public class HomeController : Controller
{
public _appsettings;
public HomeController(IOptions<AppSettings> appSettings)
{
_appsettings = appSettings;
}
}
最后,您現在可以通過在控制器中調用_appsettings.ConnectionString
來獲取連接字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.