2

Haven't worked in .net core before and I am having some issues with the connection string. I am trying to get the connection string in my controller like so

 SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["DefaultConnection"].ToString());

but I am getting an 'Object reference not set to an instance of an object.' in my controller. This is what my appsettings.json looks like

"ConnectionStrings": {
    "DefaultConnection": "Server=(server)\\\\mssqllocaldb;Database=dbName;User ID=user;Password=123123"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"

2 Answers 2

3

You can't get the connection string directly in your controller, but you can inject the configuration and then you can access the connection string like this in your controller

public class HomeController : Controller
{
    public HomeController (IConfiguration configuration)
    {
        var connectionString = configuration.GetConnectionString("DefaultConnection")
    }
}

Sign up to request clarification or add additional context in comments.

Comments

3

The use of ConfigurationManager assumes the presence of "App.config" in your project, not appsettings.json. Example:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Server=(server)\\\\mssqllocaldb;Database=dbName;User ID=user;Password=123123" />
  </connectionStrings>
</configuration>

To use

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.