首先在ConfigureServices添加app
public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("any", builder => { //builder.AllowAnyOrigin() //容許任何來源的主機訪問 builder .WithOrigins("http://*.*.*.*")//.SetIsOriginAllowedToAllowWildcardSubdomains()//設置容許訪問的域 .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials();// }); }); services.AddControllers(); }
而後新增 dom
public class CorsMiddleware { private readonly RequestDelegate _next; public CorsMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Origin")) { context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); } await _next(context); } }
而後 使用中間件async
app.UseMiddleware<CorsMiddleware>();