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

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

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

1.新建项目

.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第1张图片
.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第2张图片

2.安装程序包

使用Nuget安装所需的程序包

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

程序包版本号
.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第3张图片
.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第4张图片
查找相关程序包
.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第5张图片
选择对应版本
.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第6张图片

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

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

打开程序包管理器控制台
.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第7张图片
执行以下代码

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

.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第8张图片
解决方案中成功新增model实体类文件夹
.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第9张图片

4.新增控制器

.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第10张图片
.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第11张图片
只可修改前半部分名称
.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第12张图片
添加如下代码

 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.StId
      axios.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文档以及UI
            app.UseSwagger(c => { c.RouteTemplate = "swagger/{documentName}/swagger.json"; });
            app.UseSwaggerUI(c =>
            {
                //v1填写自定义的页面
                c.SwaggerEndpoint("v1/swagger.json", "v1");
            });
}

项目启用XML注释
.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第13张图片
编译后会生成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
{
    /// 
    /// 学生信息增删修改
    /// 
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("AllowAll")] //设置跨域处理的 代理
    public class StudentController : ControllerBase
    {
        /// 
        /// 数据库上下文
        /// 
        public readonly dotnettestContext _dotnettest = new dotnettestContext();
        /// 
        /// 获取所有学生信息
        /// 
        /// 
        [HttpGet]
        public List<TStudent> GetStudents()
        {
            var studentInfo = _dotnettest.TStudent.ToList();
            return studentInfo;
        }
        /// 
        /// 根据主键异步查询学生信息
        /// 
        /// 
        /// 
        //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;
        }
       
        /// 
        /// 通过姓名查询学生信息
        /// 
        /// 学生姓名
        /// 
        [HttpGet]
        [Route("GetByName/")]
        public async Task<List<TStudent>> GetByNameAsync(string name)
        {
            var studentInfo =await  _dotnettest.TStudent.
                Where(b => b.StName == name)
                .ToListAsync();
            return studentInfo;
        }
        /// 
        /// 通过姓名和id获取学生信息
        /// 
        /// id
        /// 姓名
        /// 
        [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;
        }
        /// 
        /// 通过原生sql查询学生信息
        /// 
        /// 
        [HttpGet]
        [Route("GetBySql")]
        public async Task<List<TStudent>> GetBySql()
        {
            var studentInfo = await _dotnettest.TStudent
                .FromSqlRaw("select * from t_student")
                .ToListAsync();
            return studentInfo;
        }
        /// 
        /// 新增学生信息
        /// 
        /// 学生对象
        /// 
        //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();

        }
        /// 
        /// 修改学生信息
        /// 
        /// 
        /// 
        /// 
        [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;
        }
        /// 
        /// 根据id删除学生
        /// 
        /// 学生id
        /// 
        //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文档
.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第14张图片

8. 项目部署

修改Program.cs,指定项目端口,并将项目配置为可外网访问。
.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第15张图片

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>();
    }
}

发布项目
.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第16张图片
.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第17张图片
cd至发布文件,执行dotnet 项目名.dll。
.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第18张图片
在浏览器中查看是否成功
.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第19张图片
.net core webApi、Entity framework core与vue axios搭建前后端分离web架构_第20张图片

你可能感兴趣的:(.net,core,asp.net,c#)