参考:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.1
官网的例子
直接去看,这里写用到的代码
创建一个model
namespace TodoApi.Models
{
public class TodoItem { public long Id { get; set; } public string Name { get; set; } public bool IsComplete { get; set; } } }
创建数据库上下文
using Microsoft.EntityFrameworkCore;
namespace TodoApi.Models
{
public class TodoContext : DbContext { public TodoContext(DbContextOptions<TodoContext> options) : base(options) { } public DbSet<TodoItem> TodoItems { get; set; } } }
Register the database context
public void ConfigureServices(IServiceCollection services) { services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList")); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
添加控制器 TodoController
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 TodoApi.Models; namespace TodoApi.Controllers { [Route("api/[controller]")] [ApiController] [EnableCors("any")] public class TodoController : ControllerBase { private readonly TodoContext _context; public TodoController(TodoContext context) { _context = context; if (_context.TodoItems.Count() == 0) { // Create a new TodoItem if collection is empty, // which means you can't delete all TodoItems. _context.TodoItems.Add(new TodoItem { Name = "Item1" }); _context.SaveChanges(); } } // GET api/todo [HttpGet] public ActionResult<List<TodoItem>> GetAll() { return _context.TodoItems.ToList(); } // GET api/todo/{id} [HttpGet("{id}", Name = "GetTodo")] public ActionResult<TodoItem> GetById(long id) { var item = _context.TodoItems.Find(id); if (item == null) { return NotFound(); } return item; } //POST /api/todo/ //Postman: Body->Raw->Json-> {"name":"Item2~","isComplete":false} //Header: Location →http://localhost:64425/api/Todo/2 [HttpPost] public ActionResult Create(TodoItem item) { _context.TodoItems.Add(item); _context.SaveChanges(); return CreatedAtRoute("GetTodo", new { id = item.Id }, item); } [HttpPut("{id}")] public ActionResult Update(long id, TodoItem item) { var todo = _context.TodoItems.Find(id); if (todo == null) { return NotFound(); } todo.IsComplete = item.IsComplete; todo.Name = item.Name; _context.TodoItems.Update(todo); _context.SaveChanges(); return NoContent(); } [HttpDelete("{id}")] public IActionResult Delete(long id) { var todo = _context.TodoItems.Find(id); if (todo == null) { return NotFound(); } _context.TodoItems.Remove(todo); _context.SaveChanges(); return NoContent(); } } }
然后可以调用了。上面代码已经设置跨域 Microsoft.AspNetCore.Cors;
跨域
1.全局配置中启用跨域处理,命名为‘any’,任何都可以访问
public void ConfigureServices(IServiceCollection services) { //配置跨域处理 services.AddCors(options => { options.AddPolicy("any", builder => { builder.AllowAnyOrigin() //允许任何来源的主机访问 .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials();//指定处理cookie }); }); }
2.在控制器或Action的方法注释上使用对应名称的 跨域规则,
[EnableCors("any")]
[Produces("application/json")]
[Route("api/Menu")] [EnableCors("any")] //设置跨域处理的 代理 public class MenuController : Controller { }
cookie
1.后台通过HttpContext上下文可以直接操作Cookie
2.前台JQuery的ajax请求,需要携带withCredentials才会将cookie的值保存到客户端