如何在没有实体框架的情况下从ASP.NET Core和Angular连接到数据库?
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" },如何在Web API控制器中获取连接字符串?
How can I get connection string in Web API controller?
string constr = ConfigurationManager.ConnectionStrings["DefaultParkingConnection"].ConnectionString;推荐答案
ASP.Net Core与ASP.Net的工作原理不同,因此您需要将appsettings.json中定义的连接字符串映射到要在整个过程中访问的类或变量.应用程序.请尝试以下方法.创建appSettings.json:
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" } }创建一个新类ConnectionStrings.cs以将appSettings.json中定义的连接字符串映射到它:
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; } } }在Startup.cs中,编写以下代码:
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"); } } }更多推荐
如何在没有实体框架的情况下连接到ASP.NET Core中的数据库?
发布评论