How can I connect to a database from ASP.NET Core and Angular without Entity Framework?
"ConnectionStrings": {
"DefaultParkingConnection": "Server=DESKTOP-CD0M0C3\\SQLEXPRESS;Database=ParkingSystem2;Trusted_Connection=True;MultipleActiveResultSets=true;User ID=sa;Password=P@ssw0rd"
},
How can I get connection string in Web API controller?
string constr = ConfigurationManager.ConnectionStrings["DefaultParkingConnection"].ConnectionString;
You could inject IConfiguration
in api controller:
public class ValuesController : Controller
{
public IConfiguration _configuration { get; }
public ValuesController(IConfiguration configuration)
{
_configuration = configuration;
string constr = _configuration.GetConnectionString("DefaultParkingConnection");
}
}
ASP.Net Core works different than ASP.Net, so you need to map the connection strings defined in appsettings.json
to a class or variable to be accessed throughout the application. Try the following approach. Create appSettings.json
:
{
"ConnectionStrings": {
"DefaultParkingConnection": "Server=DESKTOP-CD0M0C3\\SQLEXPRESS;Database=ParkingSystem2;Trusted_Connection=True;MultipleActiveResultSets=true;User ID=sa;Password=P@ssw0rd"
}
}
Create a new class ConnectionStrings.cs
to map the connection strings defined in appSettings.json
to it:
using System;
namespace Test
{
public class ConnectionStrings
{
public string DefaultParkingConnection{ get; set; }
}
}
In Startup.cs
, write the following code:
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
this.Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
//Map the configuration
var connectionSection = Configuration.GetSection("ConnectionStrings");
services.Configure<ConnectionStrings>(connectionSection );
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Configure
}
}
Now in controllers, you can easily use it without creating the instance of the class:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace Test.Controllers
{
[ApiController]
[Route("api/account")]
public class AccountController : ControllerBase
{
private readonly ConnectionStrings connectionStrings;
public AccountController(IOptions<ConnectionStrings> connectionStrings)
{
this.connectionStrings = connectionStrings.Value;
}
[HttpGet, Route("test")]
public IActionResult Test()
{
return Ok("test");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With