You must Sign In to post a response.
  • Category: .NET

    WEB API CORE WITH ADO.NET connectionstring issue

    Hi,
    I am new to web api core,I have created one web api core with ado.net application.
    I have declared a conenction string in appseeting.json,
    I am trying new access in the controller but i am getting null value?
    can any one help me how to access conenction string in controller from appsetting.sjon
    step1
    appsettins.json
    {
    "Logging": {

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

    },
    "AllowedHosts": "*",
    "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLOCALDB;Database=resource;Trusted_Connection=True;"

    }
    }

    step 2
    SqlConnection con1 = new SqlConnection(configuration.GetConnectionString("DefaultConnection"));
  • #770439
    ASP.NET Core uses dependency injection to pass the configuration settings to your classes, so Add IConfiguration to Your Controller like below
    public class YourController : Controller
    {
    private readonly string _connectionString;

    public YourController(IConfiguration configuration)
    {
    // Read the connection string
    _connectionString = configuration.GetConnectionString("DefaultConnection");
    }

    public IActionResult Index()
    {
    // Use _connectionString in your logic
    ViewData["ConnectionString"] = _connectionString; // Example of passing it to the view
    return View();
    }
    }

    Thanks!
    B.Ramana Reddy


  • Sign In to post your comments