// 設置允許所有來源跨域 app.UseCors(options => { options.AllowAnyHeader(); options.AllowAnyMethod(); options.AllowAnyOrigin(); options.AllowCredentials(); }); // 設置只允許特定來源可以跨域 app.UseCors(options => { options.WithOrigins("http://localhost:3000", "http://127.0.0.1"); // 允許特定ip跨域 options.AllowAnyHeader(); options.AllowAnyMethod(); options.AllowCredentials(); });
在Startup.cs的Configure方法加如下代碼,親測好使:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // 設置允許所有來源跨域 app.UseCors(options => { options.AllowAnyHeader(); options.AllowAnyMethod(); options.AllowAnyOrigin(); options.AllowCredentials(); }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // 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.UseMvc(); }