基于.net core 2.1,开发工具VS2017。
使用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
Scaffold-DbContext "server=ip;uid=userid;pwd=ped;port=3306;database=db;" Pomelo.EntityFrameworkCore.MySql -OutputD Models -Force
private db_gczd2020Context _Gczd2020Context = new db_gczd2020Context();
[HttpGet]
public List<TMeterinfo> GetMeterinfos()
{
var meterInfo = _Gczd2020Context.TMeterinfo.
Where(b => b.MeterId == 1)
.ToList();
return meterInfo;
}
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")] //设置跨域处理的 代理
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);
});
},
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);
});
},
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);
});
},
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);
});
},
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);
});
},
查询视图的方式与查询单表的方法一致
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);
});
},
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);
});
}
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);
});
},
安装程序包
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注释
编译后会生成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
修改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>();
}
}