asp.net core WebApi 快速入門
阿新 • • 發佈:2018-12-05
參考: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的值儲存到客戶端