[英]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.