简体   繁体   English

ASP.NET 内核 Cors 策略

[英]ASP.NET core Cors policy

I'm having problem setting up Cors policy in my ASP.NET core project.我在我的 ASP.NET 核心项目中设置 Cors 策略时遇到问题。

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAll",
            builder =>
            {
                builder
                .AllowAnyOrigin() 
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials();
            });
    });
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        services.AddMemoryCache();
}

I've tried adding app.UseCors("AllowAll");我试过添加app.UseCors("AllowAll"); in Configure(IApplicationBuilder app, IHostingEnvironment env) , tried [EnableCors("AllowAll")] before controller declaration:Configure(IApplicationBuilder app, IHostingEnvironment env)中,在 controller 声明之前尝试了[EnableCors("AllowAll")]

[Route("api/[controller]")]
[ApiController]
[EnableCors("AllowAll")]
public class TestController : ControllerBase

and before method declaration:和方法声明之前:

[HttpPost]
[EnableCors("AllowAll")]
public JsonResult Post([FromBody] dynamic request)

and no luck, I'm keep getting "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at..."没有运气,我不断收到“跨源请求被阻止:同源策略不允许在...读取远程资源”

Maybe someone can help me?也许有人可以帮助我?

I know this is too late, but can help someone,我知道这为时已晚,但可以帮助某人,

using CorsMiddleware in specified order is matters按指定顺序使用 CorsMiddleware 很重要

app.UseRouting();
app.UseCors("AllowAll");
app.UseAuthorization();
app.UseResponseCaching();
  1. The call to UseCors must be placed after UseRouting, but before UseAuthorization.对 UseCors 的调用必须放在 UseRouting 之后,但在 UseAuthorization 之前。
  2. When using Response Caching Middleware, call UseCors before UseResponseCaching使用响应缓存中间件时,在 UseResponseCaching 之前调用 UseCors

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM