简体   繁体   中英

FluentNHibernate cannot read connectionString from web.config

When I use FluentNHibernate, it is not able to read connection string from web.config. I am using ASP.NET Core Web Application (.NET Framework), Fluent NHibernate 2.0.3 and NHibernate 4.0.0.4000.

The commented way works fine to access the database, while the not commented one does not work.

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

The web.config is

<?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>

This is the error I got. Please help to see what is wrong. Thank you.

在此处输入图片说明

The structure of the project is as follow

在此处输入图片说明

First check this question I think it might solve your problem Access WebConfig in DotNet Core

Another solution is to use appsettings.json file instead.

You can do that by adding a json file to your project. Same folder as project.json file.

In your startup.cs you just map your file to your app configuration as the following:

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
    }

Now I am not sure about the static variable I created there it might not be the best way to go about it. But it gave me what I needed.

You can then use it to get your connectionstring like that :

Startup.Configuration["AppSettings:ConnectionString"]

Given that you have a ConnectionString key in your appsettings.json file.

{  
 "AppSettings": 
  {
   "ConnectionString": "" //type your connection string in here 
  }
}

What is even better is to add an AppSettings class like this:

 public class AppSettings
{
    public string ConnectionString { get; set; }
}

Now you need to map it as a service (Adding it to your middleware).

public void ConfigureServices(IServiceCollection services)
    { 
        //other services
        services.Configure<AppSettings> Configuration.GetSection("AppSettings"));
        //other services
    }

So you can inject it to your controllers:

 public class HomeController : Controller
 {
    public _appsettings;
    public HomeController(IOptions<AppSettings> appSettings)
    {
       _appsettings = appSettings;
    }
 }

Finally you can now get your connection string by calling _appsettings.ConnectionString in your controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM