1、Core WebAPI中的跨域處理 html
1.在使用WebAPI項目的時候基本上都會用到跨域處理ajax
2.Core WebAPI的項目中自帶了跨域Cors的處理,不須要單獨添加程序包json
3.使用方法簡單api
2、使用實例跨域
1.全局配置中啓用跨域處理,命名爲‘any’,任何均可以訪問cookie
public void ConfigureServices(IServiceCollection services) { //配置跨域處理 services.AddCors(options => { options.AddPolicy("any", builder => { builder.AllowAnyOrigin() //容許任何來源的主機訪問 .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials();//指定處理cookie }); }); }
2.在控制器或Action的方法註釋上使用對應名稱的 跨域規則,app
[EnableCors("any")]ui
[Produces("application/json")] [Route("api/Menu")] [EnableCors("any")] //設置跨域處理的 代理 public class MenuController : Controller { }
注:若是在控制器上指定,則控制器內 全部的Action都有對應的跨域限制。url
三 、跨域時,Cookie的訪問spa
1.後臺經過HttpContext上下文能夠直接操做Cookie
[Produces("application/json")] [Route("api/CookieOne")] [EnableCors("any")] public class CookieOneController : Controller { //後臺設置Cookie [HttpPut] public IActionResult Add() { ControllerContext.HttpContext.Response.Cookies.Append("name", "中文 ,張三丰"); return Ok(new { msg = "設置成功" }); } //後臺獲取Cookie,特別 說明對於基礎類型的返回值,默認JQuery的ajax解析失敗,最好返回IActionResult [HttpGet] public IActionResult Get() { string result = HttpContext.Request.Cookies["url"]; return Content(result); } }
2.前臺JQuery的ajax請求,須要攜帶withCredentials纔會將cookie的值保存到客戶端
var example1 = new Vue({ el: '#example1', data: { name: '空', url: '空' } }); //1.後臺添加cookie function addOne() { $.ajax({ url: urlHelper.getApi('cookieone'), type: 'put', xhrFields: { withCredentials:true //配置http跨域請求中攜帶cookie }, success: function (data) { console.info(data); //前臺獲取cookie var name = Cookies.get('name'); console.info(name); example1.name = name; //Vue中修改雙向綁定能夠經過Vue實例進行,不須要再次通知頁面(和AngularJs不一樣) } }); } addOne(); //2.前臺添加Cookie 後臺獲取 function getOne() { Cookies.set('url', 'http://www.gongjuji.net/'); $.ajax({ url: urlHelper.getApi('cookieone'), type: 'get', contentType: 'application/json', xhrFields: { withCredentials: true //配置http跨域請求中攜帶cookie }, success: function (data) { console.info(data); example1.url = data; } }); } getOne();
更多: