当前位置: 代码迷 >> 综合 >> .net core webApi、Entity framework core与vue axios搭建前后端分离web架构
  详细解决方案

.net core webApi、Entity framework core与vue axios搭建前后端分离web架构

热度:23   发布时间:2023-12-25 15:43:20.0

.net core webApi、Entity framework core与vue axios搭建前后端分离web架构

基于.net core 2.1,开发工具VS2017。

1.新建项目

在这里插入图片描述
在这里插入图片描述

2.安装程序包

使用Nuget安装所需的程序包

Microsoft.AspNetCore.All
Microsoft.AspNetCore.Mvc.Formatters.Json
Microsoft.EntityFrameworkCore.Tools
MySql.Data.EntityFrameworkCore
Pomelo.EntityFrameworkCore.MySql

程序包版本号
在这里插入图片描述
在这里插入图片描述
查找相关程序包
在这里插入图片描述
选择对应版本
在这里插入图片描述

Microsoft.AspNetCore.All
Microsoft.AspNetCore.Mvc.Formatters.Json
Microsoft.EntityFrameworkCore.Tools
MySql.Data.EntityFrameworkCore
Pomelo.EntityFrameworkCore.MySql

3.Database First通过现有数据库生成模型

打开程序包管理器控制台
在这里插入图片描述
执行以下代码

Scaffold-DbContext "server=ip;uid=userid;pwd=ped;port=3306;database=db;" Pomelo.EntityFrameworkCore.MySql -OutputD Models -Force

解决方案中成功新增model实体类文件夹
在这里插入图片描述

4.新增控制器

在这里插入图片描述

在这里插入图片描述
只可修改前半部分名称
在这里插入图片描述
添加如下代码

 private db_gczd2020Context _Gczd2020Context = new db_gczd2020Context();[HttpGet]public List<TMeterinfo> GetMeterinfos(){
    var meterInfo = _Gczd2020Context.TMeterinfo.Where(b => b.MeterId == 1).ToList();return meterInfo;}

5.配置跨域访问

Startup.cs文件中 ConfigureServices函数新增配置信息

        public void ConfigureServices(IServiceCollection services){
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);//配置跨域处理services.AddCors(options =>{
    options.AddPolicy("AllowAll", builder =>{
    builder.AllowAnyOrigin() //允许任何来源的主机访问.AllowAnyMethod().AllowAnyHeader().AllowCredentials();//指定处理cookie});});}

相应的控制器前增加跨域处理的代理

[Route("api/[controller]")]
[ApiController]
[EnableCors("any")] //设置跨域处理的 代理

6. axios与.net core webapi对数据库增删查改

6.1 查询

6.1.1 查询所有

webapi

 [HttpGet]
public List<TStudent> GetStudents()
{
    var studentInfo = _dotnettest.TStudent.ToList();return studentInfo;
}

vue代码

getData () {
    axios.get('http://localhost:54061/api/student/', {
    }).then((response) => {
    console.log(response.data)}).catch(function (error) {
    console.log(error);});},

6.1.2 按主键查询

webapi

[HttpGet("{id}")]
public async Task<ActionResult<TStudent>> GetById(int id)
{
    var studentInfo = await _dotnettest.TStudent.FindAsync(id);if (studentInfo == null){
    return NotFound();}return studentInfo;
}

vue代码

 getDataById () {
    axios.get('http://localhost:54061/api/student/2', {
    }).then((response) => {
    console.log(response.data)}).catch(function (error) {
    console.log(error);});},

6.1.3 按非主属性查询

webapi

        [HttpGet][Route("GetByName/{name}")]public async Task<List<TStudent>> GetByNameAsync(string name){
    var studentInfo =await  _dotnettest.TStudent.Where(b => b.StName == name).ToListAsync();return studentInfo;}

vue代码

   getDataByName () {
    let url = 'http://localhost:54061/api/student/GetByName/' + '小郑'axios.get(url, {
    }).then((response) => {
    console.log(response.data)}).catch(function (error) {
    console.log(error);});},

6.1.4 多条件查询

webapi

        public async Task<List<TStudent>> GetByNameAndId(int stId,string stName){
    var studentInfo = await _dotnettest.TStudent.Where(b => b.StId == stId && b.StName == stName).ToListAsync();return studentInfo;}

vue代码

 getDataByNameAndId () {
    let url = 'http://localhost:54061/api/student/GetByNameAndId'axios.get(url, {
    params: {
    stid: 2,stname: '小郑'        }}).then((response) => {
    console.log(response.data)}).catch(function (error) {
    console.log(error);});},

6.1.5 sql语句查询

webapi

        [HttpGet][Route("GetBySql")]public async Task<List<TStudent>> GetBySql(){
    var studentInfo = await _dotnettest.TStudent.FromSqlRaw("select * from t_student").ToListAsync();return studentInfo;}

vue代码

    getBySql () {
    let url = 'http://localhost:54061/api/student/GetBySql'axios.get(url).then((response) => {
    console.log(response.data)}).catch(function (error) {
    console.log(error);});},

查询视图的方式与查询单表的方法一致

6.2 新增

webapi

 [HttpPost]public async Task<ActionResult<TStudent>> PostAddStudent(TStudent tstudent){
    _dotnettest.TStudent.Add(tstudent);await _dotnettest.SaveChangesAsync();return NoContent();}

vue代码

 //保存数据saveData () {
    axios.post('http://localhost:54061/api/student/', {
    StName: 'Henr',StTel: "123456"}).then((response) => {
    console.log(response)}).catch(function (error) {
    console.log(error);});},

6.3 删除

webapi

[HttpDelete("{stid}")]public async Task<int> DeleteStudent(int stid){
    var student = await _dotnettest.TStudent.FindAsync(stid);if (student == null){
    return 300;}_dotnettest.TStudent.Remove(student);await _dotnettest.SaveChangesAsync();return 200;}

vue代码

//删除数据deleteData () {
    let url = 'http://localhost:54061/api/student/' + this.StIdaxios.delete(url, {
    }).then((response) => {
    console.log(response)}).catch(function (error) {
    console.log(error);});}

6.4 修改

webapi

        [HttpPut("{id}")]public async Task<int> putStudent(int id,TStudent student){
    if(id != student.StId){
    return 400;}_dotnettest.Entry(student).State = EntityState.Modified;await _dotnettest.SaveChangesAsync();return 200;}

vue代码

changeData () {
    let url = 'http://localhost:54061/api/student/' + '2'axios.put(url, {
    StId: 2,StName: '小郑',StTel: "123456"}).then((response) => {
    console.log(response)}).catch(function (error) {
    console.log(error);});},

7.使用swagger生成API文档

安装程序包

Microsoft.AspNetCore.StaticFiles
Swashbuckle.AspNetCore
Swashbuckle.AspNetCore.SwaggerUi

配置startup.cs

  public void ConfigureServices(IServiceCollection services){
    //加入 Swagger(加入这段)services.AddSwaggerGen(c =>{
    c.SwaggerDoc("v1", new OpenApiInfo {
     Title = "MyApi", Version = "v1" });//MyNewTestCoreAPI.XML填写成生成的XML文件var xmlPath = Path.Combine(AppContext.BaseDirectory, "MyNewTestCoreAPI.XML");c.IncludeXmlComments(xmlPath);});
}public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){
    //启用中间件,允许Swagger提供服务生成json文档以及UIapp.UseSwagger(c => {
     c.RouteTemplate = "swagger/{documentName}/swagger.json"; });app.UseSwaggerUI(c =>{
    //v1填写自定义的页面c.SwaggerEndpoint("v1/swagger.json", "v1");});
}

项目启用XML注释
在这里插入图片描述
编译后会生成XML注释文件
在这里插入图片描述
api中添加注释

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebApplication1.Models;namespace WebApplication1.Controllers
{
    /// <summary>/// 学生信息增删修改/// </summary>[Route("api/[controller]")][ApiController][EnableCors("AllowAll")] //设置跨域处理的 代理public class StudentController : ControllerBase{
    /// <summary>/// 数据库上下文/// </summary>public readonly dotnettestContext _dotnettest = new dotnettestContext();/// <summary>/// 获取所有学生信息/// </summary>/// <returns></returns>[HttpGet]public List<TStudent> GetStudents(){
    var studentInfo = _dotnettest.TStudent.ToList();return studentInfo;}/// <summary>/// 根据主键异步查询学生信息/// </summary>/// <param name="id"></param>/// <returns></returns>//api/student/1[HttpGet("{id}")]public async Task<ActionResult<TStudent>> GetById(int id){
    var studentInfo = await _dotnettest.TStudent.FindAsync(id);if (studentInfo == null){
    return NotFound();}return studentInfo;}/// <summary>/// 通过姓名查询学生信息/// </summary>/// <param name="name">学生姓名</param>/// <returns></returns>[HttpGet][Route("GetByName/")]public async Task<List<TStudent>> GetByNameAsync(string name){
    var studentInfo =await  _dotnettest.TStudent.Where(b => b.StName == name).ToListAsync();return studentInfo;}/// <summary>/// 通过姓名和id获取学生信息/// </summary>/// <param name="stId">id</param>/// <param name="stName">姓名</param>/// <returns></returns>[HttpGet][Route("GetByNameAndId/")]public async Task<List<TStudent>> GetByNameAndId(int stId,string stName){
    var studentInfo = await _dotnettest.TStudent.Where(b => b.StId == stId && b.StName == stName).ToListAsync();return studentInfo;}/// <summary>/// 通过原生sql查询学生信息/// </summary>/// <returns></returns>[HttpGet][Route("GetBySql")]public async Task<List<TStudent>> GetBySql(){
    var studentInfo = await _dotnettest.TStudent.FromSqlRaw("select * from t_student").ToListAsync();return studentInfo;}/// <summary>/// 新增学生信息/// </summary>/// <param name="tstudent">学生对象</param>/// <returns></returns>//Post:api/student[HttpPost]public async Task<ActionResult<TStudent>> PostAddStudent(TStudent tstudent){
    _dotnettest.TStudent.Add(tstudent);await _dotnettest.SaveChangesAsync();//CreatedAtAction(actionName,routeValues,value).return NoContent();}/// <summary>/// 修改学生信息/// </summary>/// <param name="id"></param>/// <param name="student"></param>/// <returns></returns>[HttpPut("{id}")]public async Task<int> putStudent(int id,TStudent student){
    if(id != student.StId){
    return 400;}_dotnettest.Entry(student).State = EntityState.Modified;await _dotnettest.SaveChangesAsync();return 200;}/// <summary>/// 根据id删除学生/// </summary>/// <param name="stid">学生id</param>/// <returns></returns>//Delete:api/student/id[HttpDelete("{stid}")]public async Task<int> DeleteStudent(int stid){
    var student = await _dotnettest.TStudent.FindAsync(stid);if (student == null){
    return 300;}_dotnettest.TStudent.Remove(student);await _dotnettest.SaveChangesAsync();return 200;}}
}

浏览器中输入地址:

http://localhost:54061/swagger/index.html

查看api文档
在这里插入图片描述

8. 项目部署

修改Program.cs,指定项目端口,并将项目配置为可外网访问。
在这里插入图片描述

namespace WebApplication1
{
    public class Program{
    public static void Main(string[] args){
    CreateWebHostBuilder(args).Build().Run();}public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>WebHost.CreateDefaultBuilder(args).UseUrls("http://*:7000").UseStartup<Startup>();}
}

发布项目
在这里插入图片描述
在这里插入图片描述
cd至发布文件,执行dotnet 项目名.dll。
在这里插入图片描述
在浏览器中查看是否成功
在这里插入图片描述
在这里插入图片描述

  相关解决方案