一、Core WebAPI中的跨域處理
- 在使用WebAPI項(xiàng)目的時(shí)候基本上都會(huì)用到跨域處理
-
Core WebAPI的項(xiàng)目中自帶了跨域Cors的處理,不需要單獨(dú)添加程序包
自帶了跨域Cors的處理
使用實(shí)例
- 全局配置中啟用跨域處理,命名為‘a(chǎn)ny’,任何都可以訪問
在Startup.cs中添加配置
public void ConfigureServices(IServiceCollection services)
{
//配置跨域處理
services.AddCors(options =>
{
options.AddPolicy("any", builder =>
{
builder.AllowAnyOrigin() //允許任何來源的主機(jī)訪問
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();//指定處理cookie
});
});
}
- 在控制器或Action的方法注釋上使用對(duì)應(yīng)名稱的 跨域規(guī)則
[EnableCors("any")]
[Route("api/[controller]")]
[ApiController]
[EnableCors("any")] //設(shè)置跨域處理的 代理
public class UserController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<User>> Get()
{
Conn mysqlGet = new Conn();
return mysqlGet.UserList();
}
}
注:如果在控制器上指定,則控制器內(nèi) 所有的Action都有對(duì)應(yīng)的跨域限制。
三 、跨域時(shí),Cookie的訪問
- 后臺(tái)通過HttpContext上下文可以直接操作Cookie
[Produces("application/json")]
[Route("api/CookieOne")]
[EnableCors("any")]
public class CookieOneController : Controller
{
//后臺(tái)設(shè)置Cookie
[HttpPut]
public IActionResult Add()
{
ControllerContext.HttpContext.Response.Cookies.Append("name", "中文 ,張三豐");
return Ok(new { msg = "設(shè)置成功" });
}
//后臺(tái)獲取Cookie,特別 說明對(duì)于基礎(chǔ)類型的返回值,默認(rèn)JQuery的ajax解析失敗,最好返回IActionResult
[HttpGet]
public IActionResult Get()
{
string result = HttpContext.Request.Cookies["url"];
return Content(result);
}
}
- 前臺(tái)JQuery的ajax請(qǐng)求,需要攜帶withCredentials才會(huì)將cookie的值保存到客戶端
var example1 = new Vue({
el: '#example1',
data: {
name: '空',
url: '空'
}
});
//1.后臺(tái)添加cookie
function addOne() {
$.ajax({
url: urlHelper.getApi('cookieone'),
type: 'put',
xhrFields: {
withCredentials:true //配置http跨域請(qǐng)求中攜帶cookie
},
success: function (data) {
console.info(data);
//前臺(tái)獲取cookie
var name = Cookies.get('name');
console.info(name);
example1.name = name; //Vue中修改雙向綁定可以通過Vue實(shí)例進(jìn)行,不需要再次通知頁面(和AngularJs不同)
}
});
}
addOne();
//2.前臺(tái)添加Cookie 后臺(tái)獲取
function getOne()
{
Cookies.set('url', 'http://www.gongjuji.net/');
$.ajax({
url: urlHelper.getApi('cookieone'),
type: 'get',
contentType: 'application/json',
xhrFields: {
withCredentials: true //配置http跨域請(qǐng)求中攜帶cookie
},
success: function (data) {
console.info(data);
example1.url = data;
}
});
}
getOne();
