简体   繁体   中英

Net 2.1, Angular 7, blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested

I am getting blocked by CORS policy. I have allowed access to all in my startup.cs This is my startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();

        services.AddDbContext<Models.StockContext>(opt => opt.UseInMemoryDatabase("item"));

        app.UseCors(builder =>
        {
            builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowCredentials()
            .AllowAnyHeader();
        });

just add this lines in your ConfigureServices part and it should work fine:

var corsBuilder = new CorsPolicyBuilder();
        corsBuilder.AllowAnyHeader();
        corsBuilder.WithMethods("GET", "POST");
        corsBuilder.AllowAnyOrigin();
        services.AddCors(options => options.AddPolicy("AllowAll",corsBuilder.Build()));

Please follow the documentation .

First, you need to enable CORS middleware inside ConfigureServices() Second, you need to tell application to use this middleware inside Configure()

Example:

In ConfigureServices() :

    services.AddCors(options =>
    {
        options.AddPolicy("AllowAllOrigins",
            builder =>
            {
                builder
                    .AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
            });
    });

In Configure() :

    app.UseCors("AllowAllOrigins");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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