https://foo.example/A.html现在页面A.html有一个ajax代码尝试读取B.html的HTML的源代码,B页面位于:
https://bar.otherB.html位于不同的域,由于同源策略限制,A.html不能做ajax请求,ajax调用将返回错误消息:
No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
W3C提供了标准来放宽同源策略,允许实现跨源资源共享(CORS),如果https://bar.other实现CORS https://foo.example/A.html能够ajax请求并读取B.html 。
builder.Services.AddCors();注意我们添加代码行使用可选AllowAnyOrigin允许每一个域能够CORS请求:
app.UseCors(builder => { // 堆代码 duidaima.com builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); });下面描述了各个方法作用
app.UseCors(builder => { builder.WithOrigins("http://www.domain.com") .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); });你也可以指定多个域在下面:
app.UseCors(builder => { builder.WithOrigins(new string[] { "https://example1.com", "https://example2.com" }) .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); });三.在action或者controller上应用CORS策略
var builder = WebApplication.CreateBuilder(args); // Adding CORS Policy builder.Services.AddCors(options => { options.AddPolicy("MyPolicy", builder => builder.WithOrigins("https://www.yogihosting.com")); }); // Add services to the container. builder.Services.AddControllersWithViews(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); // Shows UseCors with named policy. app.UseCors("MyPolicy"); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();将策略名字传递到UseCors()方法:现在将CORS策略应用到每个action或者controller
[EnableCors("MyPolicy")] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; }3.2 每个Controller
[EnableCors("MyPolicy")] public class HomeController : Controller在Controller和action上禁用CORS,使用[DisableCors]特性:
[DisableCors] public string Get(int id) { return "value"; }