1.建立web.api项目
1.1新建解决方案
1.2 新建项目
1.3 选择API
2.修改appsettings.json文件
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"MySqlConnection": "server=localhost;userid=root;password=123456;database=qchnewbak;"
},
"AllowedHosts": "*"
}
3.工具-Nuget包管理器 添加依赖包
4.创建文件夹Model,并创建数据交互文件Database,以及两个实体
public class DataBase : DbContext
{
//构造方法
public DataBase(DbContextOptions<DataBase> options)
: base(options)
{
}
#region 数据区域
public DbSet<User> User { get; set; }
public DbSet<Area> Area { get; set; }
#endregion
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
5.修改staup文件
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextPool<DataBase>(options => options.UseMySql(Configuration.GetConnectionString("MySqlConnection"), b => b.MigrationsAssembly("Core.Api")));
services.AddControllers();
#region Swagger
services.AddSwaggerGen(option =>
{
option.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "我的测试 API",
Description = "API for zhengyb",
Contact = new OpenApiContact() { Name = "郑亚波", Url = new Uri("https://www.cnblogs.com/zhengyb/") }
});
string baseUrl = System.IO.Path.Combine(AppContext.BaseDirectory, $"{typeof(Startup).Assembly.GetName().Name}.xml");
option.IncludeXmlComments(baseUrl, true);
});
#endregion
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger(); //新增的,之前的不动
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.DocumentTitle = "我的测试 API";
});
......
}
6.右侧项目,属性,生成修改xml路径
xml的文件名称一定要和Startup.cs的ConfigureServices方法的路径名对应上
string baseUrl = System.IO.Path.Combine(AppContext.BaseDirectory, $"{typeof(Startup).Assembly.GetName().Name}.xml");
option.IncludeXmlComments(baseUrl, true);
7.修改启动文件
8.NetGet包管理内,输入命令行
Add-Migration MyFirstMigration(名字。这里随意取未MyFirstMigration) 添加迁移
Update-Database 更新数据库
9.添加接口控制器
删除Collroller中原有的一个文件
添加一个新的文件,选择API控制器-空
namespace BeltScaleUI.API.Controllers
{
[Route("api/v1/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly DataBase _context;
public UserController(DataBase context)
{
_context = context;
}
#region base
/// <summary>
/// 获取单条信息
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet]
public List<User> GetById(string id)
{
var tt = _context.Set<User>().Where(c => c.id == id).ToList();
//_context.Set<User>().Add(us);
//_context.SaveChanges();
return tt;
}
/// <summary>
/// 添加
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
[HttpPost]
public JsonResult Add(User entity = null)
{
_context.Set<User>().Add(entity);
int num = _context.SaveChanges();
if (entity == null)
return JsonA.Json("参数为空");
if (num > 0) { return JsonA.Json("成功"); }
else { return JsonA.Json("失敗"); }
}
/// <summary>
/// 编辑
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
[HttpPut]
[Route("User")]
public JsonResult Update(User entity = null)
{
_context.Set<User>().Update(entity);
int num = _context.SaveChanges();
if (entity == null)
return JsonA.Json("参数为空");
if (num > 0) { return JsonA.Json("成功"); }
else { return JsonA.Json("失敗"); }
}
/// <summary>
/// 删除
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
[HttpDelete]
public JsonResult Dels(string ids = null)
{
if (ids.Length == 0)
return JsonA.Json("参数为空");
var tt = _context.Set<User>().Where(c => c.id == ids).First();
_context.Set<User>().Remove(tt);
int num = _context.SaveChanges();
if (num > 0) { return JsonA.Json("成功"); }
else { return JsonA.Json("失敗"); }
}
#endregion
}
}