本文主要介紹在Asp.net Core採用CORS方式解決跨域 關於跨域的原理介紹可參考 "Asp.net Web API 解決跨域詳解" 1 在Startup添加允許跨域的策略 2怎樣應用AnyOrigin策略 只需要在控制器頭上(或某個行為上)添加標識: 如: 3 AnyOrigin略幾乎直接完 ...
本文主要介紹在Asp.net Core採用CORS方式解決跨域
關於跨域的原理介紹可參考Asp.net Web API 解決跨域詳解
1 在Startup添加允許跨域的策略
services.AddCors(options =>
{
options.AddPolicy("AnyOrigin", builder =>
{
builder.AllowAnyOrigin() //允許任何來源的主機訪問
.AllowAnyMethod()//允許任何請求方法
.AllowAnyHeader()//允許任何請求頭
.AllowCredentials();//指定處理cookie
});
});
2怎樣應用AnyOrigin策略
只需要在控制器頭上(或某個行為上)添加標識:[EnableCors("AnyOrigin")]
如:
[Route("api/[controller]/[action]")]
[ApiController]
[EnableCors("AnyOrigin")]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
}
3
AnyOrigin略幾乎直接完全無視了“同源策略”的限制,任何客戶端都允許跨域訪問,實際項目中建議儘量不要這麼寫。
可以採用如下方式,對訪問源,HTTP請求方法及請求頭根據實際情況進行限制:
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin", builder =>
{
builder.WithOrigins("http://localhost:40197", "http://localhost:40196")
.WithHeaders("GET", "POST")
.WithHeaders("Authorization");
});
});