首页 > 解决方案 > 仅在 API 的一项操作中出现 CORS 策略错误

问题描述

我制作了一个 .net core (2.2) API,一开始我遇到了 Access-Control-Allow-Origin 错误,但是当我在 Startup.cs 中添加 CORS 策略时,它得到了修复。问题是我添加了另一个 POST 方法,它抛出了同样的错误。我已经尝试了很多我在互联网上看到的建议,但没有一个有效。

顺便说一句,我可以访问服务器。

我在ConfigureServices函数中添加了这一行:

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

            });

Configure函数中我添加了这个:

app.UseCors();

这是引发错误的 post 方法:

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

这就是我调用 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);
    });
}

这是错误:

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.

编辑:

这是我的启动:

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

标签: c#.net-coreasp.net-core-webapi

解决方案


尝试使用以下语法代替默认的 cors 策略来启动您的启动:


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

并且您的 UseCors 方法应该介于 app.UseHttpsRedirection()、app.UseRouting 和 app.UseAuthourization 之间

 app.UseHttpsRedirection(); // if needed
 app.UseStaticFiles(); //if needed
app.UseRouting()
....
.....
app.UseCors("AllowAllOrigins");

....
....
app.UseAuthorization(); // if you need the one

推荐阅读