1. 前言
笔者最近跟着微软官方文档学习.net core WebAPI,但发现其对 WebAPI 连接数据库、读取数据库方面讲得不够细致明了。写此文的目的,即实现 .net core WebAPI 的 GET、POST 方法访问数据库,并输出结果。
2. 开发准备
2.1 操作系统
Windows 10 / Windows 7
2.2 .net core sdk
.net core 2.2
下载地址:https://dotnet.microsoft.com/download
2.3 开发工具
Visual Studio 2017
3. 创建 .net core WebAPI 项目
用 Visul Studio 2017 新建项目,在出现的对话框中选择 .NET Core -> ASP.NET Core Web 应用程序,并输入项目名称。
单击【确定】后,在出现的对话框中选择【API】,注意不要勾选【启用Docker支持】,身份验证方式为【不进行身份验证】,然后单击【确定】。
之后生成了相应的模板项目,如下图所示。
从图中可以看到,默认的项目文件中已经包含了 Controllers。其为控制器文件夹,用来进行业务编写的代码,我们基本上需要在这个文件中进行数据的传出与接收。相应的,我们还可以进行各个文件创建,进行层次区分,也可以建立单独的类项目,进行层次区分,如控制层,服务业务层,数据连接层,模型实体层。
另外,
appsettings:配置文件,此处可以编写一些常量设置,然后在程序中进行读取。
Program:项目启动文件。
Startup:项目配置设置文件。
4. 连接数据库
4.1 连接 MySQL 数据库
首先,利用 Visul Studio 2017 中的 nuget 安装 MySql.Data.EntityFrameworkCore,输入如下命令。
Install-Package MySql.Data.EntityFrameworkCore -Version 8.0.15
也可以参照 https://www.nuget.org/packages/MySql.Data.EntityFrameworkCore 中其它方法。其它数据库提供程序可参照 https://docs.microsoft.com/zh-cn/ef/core/providers/index。
安装成功后可以在依赖项中看到 MySql.Data.EntityFrameworkCore
接下来创建一个数据表结构,并添入示例数据,例如下图。
C#中创建对应的实体类,另外创建一个类继承dbContext,dbContext是EF框架中非常重要的一个环节,是建立实体类与数据库连接的桥梁,具体的原理,这里不进行赘述。
创建过程如下代码所示(注意要自行在项目中添加 Models 文件夹,并添加实体类文件,如 Person.cs)。
Models/Person.cs
using System.ComponentModel.DataAnnotations;
namespace WebApi.Models
{
public class Person
{
[Key]
public int Id { get; set; }
[MaxLength(20)]
public string Name { get; set; }
[MaxLength(3)]
public int Age { get; set; }
}
}
Models/CoreDbContext.cs
using Microsoft.EntityFrameworkCore;namespace WebApi.Models
{
public class CoreDbContext : DbContext
{
public virtual DbSet<Person> Person { get; set; } //创建实体类添加Context中
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseMySQL(@"server=localhost;uid=YourUserId;pwd=YourPassword;
port=3306;database=DbName;sslmode=Preferred;");
}
}
}
}
下面改写 ValuesController.cs 中相关代码,以测试 GET 方法。
Controllers/ValuesController.cs
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using WebApi.Models;
namespace WebApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public List<Person> Get()
{
using (CoreDbContext _coreDbContext = new CoreDbContext())
{
return _coreDbContext.Set<Person>().ToList();
}
}
......
}
}
调试运行结果如下
表示数据库已经连接成功,并以 GET 方法取得数据。
4.2 连接数据库的写法改进
针对上述的连接属性的情况来看,我们不应该把连接的属性编写在代码中,因此我们要设计一下,把连接的属性编写在配置文件中,对appsettings.json,Startup.cs,CoreDbContext.cs进行相关的配置,如下所示。
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "server=localhost;uid=YourUserId;pwd=YourPassword;port=3306;database=DbName;sslmode=Preferred;"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
Startup.cs
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//连接 mysql 数据库,添加数据库上下文
services.AddDbContext<CoreDbContext>(options =>
options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
CoreDbContext.cs
using Microsoft.EntityFrameworkCore;
namespace WebApi.Models
{
public class CoreDbContext : DbContext
{
public virtual DbSet<Person> Person { get; set; } //创建实体类添加Context中
public CoreDbContext(DbContextOptions<CoreDbContext> options) : base(options)
{
}
}
}
上述代码高亮部分就是要修改或添加的内容,这时其实是已经把coreDbContext注入到容器中进行操作,而容器中对Context的注入方式为瞬时注入,因此后面要用到依赖注入的时候,很多时候,在数据层使用context的时候需要把对应的注入都设计为瞬时注入的形式,此处就不进行过多的提及。
我们在进行测试一下,这下我们就不用自己进行context的new操作,由于我们一开始进行设置的时候就已经进行了依赖注入的形式,不过,.netCore中只有构造注入,没有属性注入,因此我们就用构造注入的方式进行,如下所示。
Controllers/ValuesController.cs
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using WebApi.Models;
namespace WebApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly CoreDbContext _coreDbContext;
public ValuesController(CoreDbContext coreDbContext)
{
_coreDbContext = coreDbContext;
}
// GET api/values
[HttpGet]
public List<Person> Get()
{
return _coreDbContext.Set<Person>().ToList();
}
......
}
}
至此写法改进完成。
4.3 关于 post 方法
在 Controllers/ValuesController.cs 中将模板文件的 Post 方法替换为
// POST api/values
[HttpPost]
public List<Person> Post()
{
return _coreDbContext.Set<Person>().ToList();
}
发布API后(搭建及发布过程此处不做讲解),用 Postman 测试。由下图可以看到获取了返回值。
【参考】开源中国:.netCore搭建WebAPI,以及MySQL,SQL server数据库连接方式