什么是 Core
Core 是一个跨平台的高性能开源框架,用于生成启用云且连接 Internet 的新式应用。
简单来说,就是比原来的新增了跨平台
Core 包含了Core MVC和Core Web API两部分,今天主要介绍 Core Web API开发的常用技巧。 Core 支持使用 C# 创建 RESTful 服务,也称为 Web API。
控制器Controllers
Web API 包含一个或多个派生自ControllerBase的控制器类。Web API 项目模板提供了一个入门版控制器:
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Mvc;namespace WebAPI.Controllers{[Route("api/[controller]")][ApiController]public class ValuesController : ControllerBase{// GET api/values[HttpGet]public ActionResult<IEnumerable<string>> Get(){return new string[] { "value1", "value2" };}// GET api/values/5[HttpGet("{id}")]public ActionResult<string> Get(int id){return "value";}// POST api/values[HttpPost]public void Post([FromBody] string value){}// PUT api/values/5[HttpPut("{id}")]public void Put(int id, [FromBody] string value){}// DELETE api/values/5[HttpDelete("{id}")]public void Delete(int id){}}}
所以你每次在VS中Debug的时候,都会打开默认浏览器,然后跳转到http://localhost:3019/api/values
注意,不要使用Controller的派生类来处理Web API的请求,Controller的派生类是用来处理Web页面的,简单来说,就是返回一个页面而不是接口。
ControllerBase
类提供了很多用于处理 HTTP 请求的属性和方法。 我自己常用的如下:
404
return NotFound()
400
return BadRequest()
200(主要用于GET请求)
return Ok()
201(创建成功,主要用于POST请求)
return Created(string uri, object value);
这里提一下,如果想在返回状态响应码的同时返回自定义的json格式信息,可以这样做
在Models目录下定义一个返回信息类
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using ponentModel.DataAnnotations;using Newtonsoft.Json;namespace WebAPI.Models{public class ReturnMessage{ public int code { get; set; }public string message { get; set; }}}
这个模型不需要映射数据库的表,因为我们不需要去增删改查数据库 。然后在接口里新建对象,直接塞进返回值。
// GET: api/test/getresultmessage[HttpGet("getresultmessage")]public async Task<ActionResult<NewAURequest>> GetBooleanSurvey(string titleId){try{ReturnMessage returnMessage = new ReturnMessage();returnMessage.message = "ok";returnMessage.code = 200;return Ok(returnMessage);} catch (Exception ex){return BadRequest();}}
这样访问http://127.0.0.1:3019/api/getresultmessage就能返回这样的json格式数据。
{"code": 200,"message": "ok"}
关于路由
这个其实也是包含在控制器里的,但是我觉得比较重要,所以单独拿出来讲一下
当你在Models目录下创建一个TodoController的时候,这个控制器的根路由就是由下面这个控制,默认的如下
namespace TodoApi.Controllers{[Route("api/[controller]")][ApiController]public class TodoController : ControllerBase{private readonly TodoContext _context;
对应的根路由就是http://127.0.0.1:3019/api/todo
将[controller]
替换为控制器的名称,按照惯例,在控制器类名称中去掉“Controller”后缀。对于此示例,控制器类名称为“Todo”控制器,因此控制器名称为“todo”****。 Core 路由不区分大小写。
模型Models
Web API接口开发无非增删改查,那么就得有对应的表数据,从简单的单表开始,没有关联关系。
在Models目录下添加模型类
namespace TodoApi.Models{public class TodoItem{public long Id { get; set; }public string Name { get; set; }public bool IsComplete { get; set; }}}
这里扩展一下其他常用字段的数据类型
// guidpublic Guid Id { get; set; }// intpublic int Id { get; set; }// Timepublic DateTime submitTime { get; set; }
添加数据库上下文,位置也可以放在Models目录下
using Microsoft.EntityFrameworkCore;namespace TodoApi.Models{public class TodoContext : DbContext{public TodoContext(DbContextOptions<TodoContext> options): base(options){}public DbSet<TodoItem> TodoItems { get; set; }}}
注册数据库上下文(Startup.cs文件,位于项目根路径下)
删除未使用的using
声明。将数据库上下文添加到 DI 容器。指定数据库上下文将使用内存中数据库。
// Unused usings removedusing Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Mvc;using Microsoft.EntityFrameworkCore;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using TodoApi.Models;namespace TodoApi{public class Startup{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the //container.public void ConfigureServices(IServiceCollection services){services.AddDbContext<TodoContext>(opt =>opt.UseInMemoryDatabase("TodoList"));services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);}// This method gets called by the runtime. Use this method to configure the HTTP //request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{// The default HSTS value is 30 days. You may want to change this for // production scenarios, see https://aka.ms/aspnetcore-hsts.app.UseHsts();}app.UseHttpsRedirection();app.UseMvc();}}}
剩下的我不想复制粘贴了,自己去看官网的文档/zh-cn/aspnet/core/web-api/?view=aspnetcore-2.1
常用的Controller的用法
场景一
单表查询多条数据
假设有张表Person,包含Id和Name,Age,模型类如下:
namespace TodoApi.Models{public class Person{public Guid Id { get; set; }public string Name { get; set; }public int Age{ get; set; }}}
PersonController
// GET: api/getpersonlist[HttpGet("getpersonlist")]public IEnumerable<Person> GetPersonList(){try{var definitionView = _context.Person;return definitionView;}catch (Exception ex){return (IEnumerable<Person>)BadRequest();}}
访问http://127.0.0.1:3019/api/person/getpersonlist
{{"id": "020f8a77-b098-46b3-a708-211d9e4bffba","name": "Mike","age": 20},{"id": "616F9F07-931C-4CE3-BCC5-B4EC417076FC","name": "Jake","age": 18}}
场景二
单表查询多条数据(URL携带参数)
假设我知道这个人的名字,需要查询单条数据
http://127.0.0.1:3019/api/person/getpersonlist/Mike,这个URL多了个参数
重新写一个方法映射新的URL请求
// GET: api/getpersonbyname/xxx[HttpGet("getpersonbyname/{name}")]public async Task<ActionResult<Person>> GetPersonByName(string name){try{var definitionView = await _context.Person.FirstOrDefaultAsync(o => o.Name == name);return definitionView;}catch (Exception ex){return BadRequest();}}
{"id": "020f8a77-b098-46b3-a708-211d9e4bffba","name": "Mike","age": 20}
场景三
关联表查询单条数据(URL携带参数)
待续...