本文将介绍在Windows 10操作系统上,用Visual Studio 2019开发一个基于MySQL数据库的WebApi项目,并发布到银河麒麟高级服务器操作系统V10上的详细过程。
1. 创建项目,选择ASP.NET Core Web应用程序
2. 确认项目名称后,选择创建
3. 选择.NET Core框架,ASP.NET Core 3.1版本,选择API项目类型,点击创建
4. 按下图,打开NuGet管理界面
5. 切换到浏览标签
6. 安装Microsoft.EntityFrameworkCore.Tools 3.1.9
7. 参考上述方法,依次完成安装:
Microsoft.EntityFrameworkCore 3.1.9
MySql.Data.EntityFrameworkCore 8.0.22
8. 更新NuGet数据库
按照下图程序包管理打开控制台
输入Update-Database
1. 本地已准备好MySQL8数据库sbtest,其中表结果及数据如下
DROP TABLE IF EXISTS `sbtest1`;
CREATE TABLE `sbtest1` (
`id` int NOT NULL AUTO_INCREMENT,
`k` int NOT NULL DEFAULT '0',
`c` char(120) NOT NULL DEFAULT '',
`pad` char(60) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
KEY `k_1` (`k`)
) ENGINE=InnoDB AUTO_INCREMENT=1000003 DEFAULT CHARSET=utf8mb4;
LOCK TABLES `sbtest1` WRITE;
INSERT INTO `sbtest1` VALUES (1000001,1,'1','1'),(1000002,2,'2','2');
UNLOCK TABLES;
2. 打开cmd,切换到当前项目目录下。检查dotnet版本信息,参考如下
C:\Users\yidam>cd "C:\Users\yidam\source\repos\WebApplication1\WebApplication1"
C:\Users\yidam\source\repos\WebApplication1\WebApplication1>dotnet --info
.NET SDK (反映任何 global.json):
Version: 5.0.100
Commit: 5044b93829
运行时环境:
OS Name: Windows
OS Version: 10.0.14393
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\5.0.100\
Host (useful for support):
Version: 5.0.0
Commit: cf258a14b7
.NET SDKs installed:
2.1.518 [C:\Program Files\dotnet\sdk]
3.1.403 [C:\Program Files\dotnet\sdk]
5.0.100 [C:\Program Files\dotnet\sdk]
.NET runtimes installed:
Microsoft.AspNetCore.All 2.1.22 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
Microsoft.AspNetCore.All 2.1.23 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
Microsoft.AspNetCore.App 2.1.22 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.AspNetCore.App 2.1.23 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.AspNetCore.App 3.1.9 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.AspNetCore.App 5.0.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.NETCore.App 2.1.22 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.NETCore.App 2.1.23 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.NETCore.App 3.1.9 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.NETCore.App 5.0.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.WindowsDesktop.App 3.1.9 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
Microsoft.WindowsDesktop.App 5.0.0 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
To install additional .NET runtimes or SDKs:
https://aka.ms/dotnet-download
C:\Users\yidam\source\repos\WebApplication1\WebApplication1>
3. 执行反向工程指令
dotnet ef dbcontext scaffold "server=localhost;port=3306;database=sbtest;uid=root;pwd=abcDEF123___;CharSet=utf8mb4" Pomelo.EntityFrameworkCore.Mysql -f -o Models
结果
C:\Users\yidam\source\repos\WebApplication1\WebApplication1>dotnet ef dbcontext scaffold "server=localhost;port=3306;database=sbtest;uid=root;pwd=abcDEF123___;CharSet=utf8mb4" Pomelo.EntityFrameworkCore.Mysql -f -o Models
Build started...
Build succeeded.
此时项目自动生成了一个Models目录,结构如下
其中
Efmigrationshistory.cs
using System;
using System.Collections.Generic;
namespace WebApplication1.Models
{
public partial class Efmigrationshistory
{
public string MigrationId { get; set; }
public string ProductVersion { get; set; }
}
}
Sbtest1.cs
using System;
using System.Collections.Generic;
namespace WebApplication1.Models
{
public partial class Sbtest1
{
public int Id { get; set; }
public int K { get; set; }
public string C { get; set; }
public string Pad { get; set; }
}
}
sbtestContext.cs
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace WebApplication1.Models
{
public partial class sbtestContext : DbContext
{
public sbtestContext()
{
}
public sbtestContext(DbContextOptions
: base(options)
{
}
public virtual DbSet
public virtual DbSet
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseMySql("server=localhost;port=3306;database=sbtest;uid=root;pwd=abcDEF123___;charset=utf8mb4", x => x.ServerVersion("8.0.22-mysql"));
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity
{
entity.HasKey(e => e.MigrationId)
.HasName("PRIMARY");
entity.ToTable("__efmigrationshistory");
entity.Property(e => e.MigrationId)
.HasColumnType("varchar(150)")
.HasCharSet("utf8mb4")
.HasCollation("utf8mb4_bin");
entity.Property(e => e.ProductVersion)
.IsRequired()
.HasColumnType("varchar(32)")
.HasCharSet("utf8mb4")
.HasCollation("utf8mb4_bin");
});
modelBuilder.Entity
{
entity.ToTable("sbtest1");
entity.HasIndex(e => e.K)
.HasName("k_1");
entity.Property(e => e.Id).HasColumnName("id");
entity.Property(e => e.C)
.IsRequired()
.HasColumnName("c")
.HasColumnType("char(120)")
.HasDefaultValueSql("''")
.HasCharSet("utf8mb4")
.HasCollation("utf8mb4_0900_ai_ci");
entity.Property(e => e.K).HasColumnName("k");
entity.Property(e => e.Pad)
.IsRequired()
.HasColumnName("pad")
.HasColumnType("char(60)")
.HasDefaultValueSql("''")
.HasCharSet("utf8mb4")
.HasCollation("utf8mb4_0900_ai_ci");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
1. 右键Controllers目录,添加一个控制器
2. 选择“MVC 控制器 - 空”
选择“API 控制器 - 空”
3. 编辑ValuesController.cs内容如下
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly sbtestContext context = new sbtestContext();
// GET api/values
[HttpGet]
public ActionResult
{
return context.Sbtest1.ToList();
}
// GET api/values/5
[HttpGet("{id}")]
public ActionResult
{
var item = context.Sbtest1.Where(c => c.Id == id).SingleOrDefault();
return item;
}
// POST api/values
[HttpPost]
public void Post([FromBody] Sbtest1 value)
{
context.Sbtest1.Add(value);
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] Sbtest1 value)
{
if (value.Id != id)
{
throw new Exception("id not equeal");
}
context.Sbtest1.Update(value);
context.SaveChanges();
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
var item = context.Sbtest1.FirstOrDefault(c => c.Id == id);
context.Sbtest1.Remove(item);
context.SaveChanges();
}
}
}
1. VS启动项目
2. 访问/api/values/
1. VS2019发布项目
得到发布输出
已启动生成…
1>------ 已启动生成: 项目: WebApplication1, 配置: Release Any CPU ------
1>C:\Users\yidam\source\repos\WebApplication1\WebApplication1\Models\sbtestContext.cs(25,10,25,214): warning CS1030: #警告:“To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.”
1>WebApplication1 -> C:\Users\yidam\source\repos\WebApplication1\WebApplication1\bin\Release\netcoreapp3.1\WebApplication1.dll
1>已完成生成项目“WebApplication1.csproj”的操作。
2>------ 发布已启动: 项目: WebApplication1, 配置: Release Any CPU ------
正在连接到 C:\Users\yidam\source\repos\WebApplication1\WebApplication1\bin\Release\netcoreapp3.1\publish\...
WebApplication1 -> C:\Users\yidam\source\repos\WebApplication1\WebApplication1\bin\Release\netcoreapp3.1\WebApplication1.dll
WebApplication1 -> C:\Users\yidam\source\repos\WebApplication1\WebApplication1\obj\Release\netcoreapp3.1\PubTmp\Out\
Web 应用已成功发布 file:///C:/Users/yidam/source/repos/WebApplication1/WebApplication1/bin/Release/netcoreapp3.1/publish/
========== 生成: 成功 1 个,失败 0 个,最新 0 个,跳过 0 个 ==========
========== 发布: 成功 1 个,失败 0 个,跳过 0 个 ==========
2. 通过FileZilla将publish目录上传到服务器/root/下
3. ssh登陆服务器,进入/root/publish目录,启动web服务
[root@localhost ~]# cd /root/publish/
[root@localhost publish]# dotnet WebApplication1.dll
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: /root/publish
4. 在服务器本地用curl检测接口
[root@localhost ~]# curl https://localhost:5001/api/values -k
[{"id":1000001,"k":1,"c":"1","pad":"1"},{"id":1000002,"k":2,"c":"2","pad":"2"}]
服务器系统信息
[root@localhost ~]# cat /etc/kylin-release
Kylin Linux Advanced Server release V10 (Azalea)
[root@localhost ~]# dotnet --info
.NET Core SDK (reflecting any global.json):
Version: 3.1.402
Commit: 9b5de826fd
Runtime Environment:
OS Name: kylin
OS Version: V10
OS Platform: Linux
RID: linux-arm64
Base Path: /root/dotnet/sdk/3.1.402/
Host (useful for support):
Version: 3.1.8
Commit: 9c1330dedd
.NET Core SDKs installed:
3.1.402 [/root/dotnet/sdk]
.NET Core runtimes installed:
Microsoft.AspNetCore.App 3.1.8 [/root/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 3.1.8 [/root/dotnet/shared/Microsoft.NETCore.App]
To install additional .NET Core runtimes or SDKs:
https://aka.ms/dotnet-download
采用.NET Core 框架,可以轻松完成ASP.NET C# Web项目迁移到国产银河麒麟高级服务器操作系统V10上。
作者:叶强