简体   繁体   中英

How do I get a valid connection string in .NET Core Web App?

This is my code but when I run it, I get a connection string that is always null . I also have the EntityFrameworkCore and SqlServer NuGet packages installed to.

The error I get is this:

System.NullReferenceException: 'Object reference not set to an instance of an object.' _connectionStrings was null.

appSettings.Development.json

{
    "Logging": {
            "LogLevel": {
                "Default": "Information",
                "Microsoft": "Warning",
                "Microsoft.Hosting.Lifetime": "Information"
            }
    },

    "ConnectionStrings": {
            "MyDataContext": "[actual connection string]"
        }
}

Startup.cs

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();

        services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
        
        services.AddDbContext<MyDataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyDataContext")));

    }
}

ConnectionStrings.cs

public class ConnectionStrings
{
    public string MyDataContext { get; set; }
}

MyDataContext

public class MyDataContext : DbContext
{
    public MyDataContext(DbContextOptions<MyDataContext> options) : base(options)
    {
    }
}

Index.cs.html

public class IndexModel : PageModel
{
    private readonly ConnectionStrings _connectionStrings;


    public IndexModel(ConnectionStrings connectionStrings)
    {
        _connectionStrings = connectionStrings;
    }

    public void OnGet()
    {
        StringBuilder sb = new StringBuilder();

        string sql = "SELECT * FROM MyTable";

        string connectionString = _connectionStrings.MyDataContext;
        SqlConnection conn = new SqlConnection(connectionString);
        conn.Open();

        SqlCommand command = new SqlCommand(sql, conn);
        SqlDataReader dr = command.ExecuteReader();

        while (dr.Read())
        {
            sb.Append(dr[0]);
        }

        conn.Close();

    ...
        // Do more stuff with the sql data here
    }
}

I also get a null reference to the object connection string. What am I missing?

Edit

I have added the constructor and now get this error:

InvalidOperationException: Unable to resolve service for type 'MyProject.ConnectionStrings' while attempting to activate 'MyProject.Pages.IndexModel'.

All the classes have namespace of MyProject with the exception of MyProject.Pages for the IndexModel page.

Solved

    private readonly ConnectionStrings _connectionStrings;
    
    public IndexModel(IOptions<ConnectionStrings> connectionStrings)
    {
        _connectionStrings = connectionStrings.Value;
    }

Understaing DI and the Options pattern are important and need further reading.

Be careful, The Appsetting.Development.json is split file and You must add this file to your configuration in Startup, like.

public static IWebHost BuildWebHost(string[] args)
{
    return new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var env = hostingContext.HostingEnvironment;
            config.AddJsonFile("appsettings.json", optional: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
            config.AddEnvironmentVariables();
        })
        .UseStartup<Startup>()
        .Build();

}

So you can add ConnectionString to Development and Production file by Env Environment

-- Priority for reading section -> 1 - AppSettings.Json 2 - AppSetting.{Env}.Json

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