[ApiController] [Route("someURL/[controller]")] public class ExampleController : ControllerBase一.什么是Web API
Web API的工作是传输数据在互联网,这些数据传输使用了HTTP协议的请求方法,我们众所周知的HTTP动词,常用的HTTP 动词有GET,POST,PUT,PATCH和DELETE, Web API使用JSON和XML文件格式的数据在互联网上传输数据。
3.5 使得Web API返回的错误基于 RFC 7807 规范 ,这使得使用不同技术(如Java、Ruby、ASP.NET Core等)创建的Web API能够无缝地相互通信,而不会出现任何问题。
namespace AspNetCore.APIControllers.Models { public class Reservations { public int Id { get; set; } public string Name { get; set; } public string StartLocation { get; set; } public string EndLocation { get; set; } } }接下来在Models文件夹添加一个文件IRepository.cs,接口定义如下:
namespace AspNetCore.APIControllers.Models { public interface IRepository { IEnumerable<Reservation> Reservations { get; } Reservation this[int id] { get; } Reservation AddReservation(Reservation reservation); Reservation UpdateReservation(Reservation reservation); void DeleteReservation(int id); } }最后,添加一个Repository类实现该接口:
using Microsoft.AspNetCore.Mvc; namespace AspNetCore.APIControllers.Models { public class Repository : IRepository { private Dictionary<int, Reservation> items; public Repository() { items = new Dictionary<int, Reservation>(); new List<Reservation> { new Reservation {Id=1, Name = "Ankit", StartLocation = "New York", EndLocation="Beijing" }, new Reservation {Id=2, Name = "Bobby", StartLocation = "New Jersey", EndLocation="Boston" }, new Reservation {Id=3, Name = "Jacky", StartLocation = "London", EndLocation="Paris" } }.ForEach(r => AddReservation(r)); } public Reservation this[int id] => items.ContainsKey(id) ? items[id] : null; public IEnumerable<Reservation> Reservations => items.Values; public Reservation AddReservation(Reservation reservation) { if (reservation.Id == 0) { int key = items.Count; while (items.ContainsKey(key)) { key++; }; reservation.Id = key; } items[reservation.Id] = reservation; return reservation; } public void DeleteReservation(int id) => items.Remove(id); public Reservation UpdateReservation(Reservation reservation) => AddReservation(reservation); } }这个类包含的属性和方法基本增删改查操作并且所有的reservation对象存储在字典类型中,这些方法和属性为:
builder.Services.AddSingleton<IRepository, Repository>();五. Web API控制器
using AspNetCore.APIControllers.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.JsonPatch; using Microsoft.AspNetCore.Mvc; namespace AspNetCore.APIControllers.Controllers { [Route("api/[controller]")] [ApiController] public class ReservationController : ControllerBase { private IRepository repository; public ReservationController(IRepository repo) => repository = repo; // 堆代码 duidaima.com [HttpGet] public IEnumerable<Reservation> Get() => repository.Reservations; [HttpGet("{id}")] public ActionResult<Reservation> Get(int id) { if (id == 0) return BadRequest("Value must be passed in the request body."); return Ok(repository[id]); } [HttpPost] public Reservation Post([FromBody] Reservation res) => repository.AddReservation(new Reservation { Name = res.Name, StartLocation = res.StartLocation, EndLocation = res.EndLocation }); [HttpPut] public Reservation Put([FromForm] Reservation res) => repository.UpdateReservation(res); [HttpPatch("{id}")] public StatusCodeResult Patch(int id, [FromBody] JsonPatchDocument<Reservation> patch) { var res = (Reservation)((OkObjectResult)Get(id).Result).Value; if (res != null) { patch.ApplyTo(res); return Ok(); } return NotFound(); } [HttpDelete("{id}")] public void Delete(int id) => repository.DeleteReservation(id); } }
注意:控制器继承ControllerBase类并且有[ApiController]特性使用到该类上,控制器从构造函数中获取IRepository对象使用依赖注入方法
[HttpGet] public IEnumerable<Reservation> Get() => repository.Reservations;正如你看到了这个方法以JSON格式在浏览器中返回了所有的对象。