'CORS policy error in only one action of API

I've made a .net core (2.2) API, at the beginning I was getting the Access-Control-Allow-Origin error, but it was fixed when I added a CORS policy in the Startup.cs. The problem is that I added another POST method and it's throwing the same error. I've tried with a lot of suggestions that I saw on internet but none of them works.

By the way, I have access to the server.

I've added this lines in the ConfigureServices function:

services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                {
                    builder.AllowAnyOrigin();
                    builder.AllowAnyMethod();
                    builder.AllowAnyHeader();
                    builder.AllowCredentials();
                });

            });

In the Configure function I added this:

app.UseCors();

This is the post method that throws the error:

[HttpPost]
    public async Task<ActionResult<IActionResult>> PostRackSections(int rows, int cols)
    {
        var lastRackSlot = _context.RackSlots.OrderBy(rs => rs.Row).ThenBy(rs => rs.Column).Last();

        for (byte i = (byte)(lastRackSlot.Row.ElementAt(0) + 1); i <= lastRackSlot.Row.ElementAt(0) + rows; i++)
        {
            for (int j = 1; j <= lastRackSlot.Column; j++)
            {
                _context.RackSlots.Add(new RackSlots { Row = Encoding.ASCII.GetString(new byte[] { i }), Column = j, Enabled = true });
            }
        }

        for (int j = lastRackSlot.Column + 1; j <= lastRackSlot.Column + cols; j++)
        {
            for (byte i = (byte)'A'; i <= lastRackSlot.Row.ElementAt(0); i++)
            {

                _context.RackSlots.Add(new RackSlots { Row = Encoding.ASCII.GetString(new byte[] { i }), Column = j, Enabled = true });
            }
        }

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateException ex)
        {
            throw;
        }

        return NoContent();
    }

And this is how I'm calling the API:

const fnAddNewSlots = () => {
    let rows = $("#ntbRows").val();
    let cols = $("#ntbCols").val();

    $.post("url", (data) => {
        toastr.success("New slots added successfully");
    }).fail((e) => {
        toastr.error("Error trying to add new slots");
        console.log(e);
    });
}

This is the error:

Access to XMLHttpRequest at 'url' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

EDIT:

This is my startup:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRouting();

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

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddDbContext<context>();

        // Register the Swagger generator, defining 1 or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
                Title = "API",
                Description = "API",

            });

            // Set the comments path for the Swagger JSON and UI.
            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            c.IncludeXmlComments(xmlPath);
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseCors("AllowAllOrigins");

        // Enable middleware to serve generated Swagger as a JSON endpoint
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("v1/swagger.json", "API");
        });


        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();
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source