繁花如伊
我认为您所需要的只是@Praneet 提到的以下内容。创建全访问策略services .AddCors(options => options .AddPolicy("WideOpen", p => p .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()) );您还需要一个Configure方法来全局启用它public void Configure(IApplicationBuilder app, IHostingEnvironment env){ app.UseCors("WideOpen");}更新的答案services .AddCors(options => options .AddPolicy("WideOpen", p => p .SetIsOriginAllowedToAllowWildcardSubdomains() .WithOrigins("*") .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()) );根据允许的来源所需的文件。 SetIsOriginAllowedToAllowWildcardSubdomains所以我已经设置WithOrigins使用通配符更新的答案 2好的,我对你的问题有个想法。我认为这不是理想或推荐的解决方案,但它会起作用。您可以有一个中间件,它为每个请求注入响应标头,这些请求需要允许 AnyOrigin、AnyMethod 和 AnyHeader 以及凭据。但是,它只会Access-Control-Allow-Origin为请求中存在的 Origin 添加标头,因此允许任何来源。如果 Ajax 检查不起作用,您可以将其删除。唯一的缺点是,它将为所有请求注入标头。public class WideOpenCorsMiddleware{ private readonly RequestDelegate _next; public WideOpenCorsMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { var response = context.Response; // check if it's an ajax request if (context.Request.Headers != null && context.Request.Headers["X-Requested-With"] == "XMLHttpRequest") { response.Headers.Add("Access-Control-Allow-Origin", new[] { (string)context.Request.Headers["Origin"] }); response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept" }); response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" }); response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" }); response.StatusCode = 200; } // if not a pre-flight request if (context.Request.Method != "OPTIONS") { await _next(context); } }}你也可以有这个扩展方法,这样你就可以很容易地在Configure方法中使用它。// Extension method used to add the middleware to the HTTP request pipeline.public static class MiddlewareExtensions{ public static IApplicationBuilder UseWideOpenCors(this IApplicationBuilder builder) { return builder.UseMiddleware<WideOpenCorsMiddleware>(); }}最后,在Configure方法中,添加以下行,可能在顶部:public void Configure(IApplicationBuilder app, IHostingEnvironment env){ app.UseWideOpenCors();}