简体   繁体   中英

JQuery Post to ASP.NET Core results in CORS error

I have an ASP.NET Core API and a html-css-js client side. I try to send a post request to said API, but Firefox throws an error that the same origin policy forbids reading of external resource.

The Startup.cs looks like this:

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.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddControllers()
            .AddNewtonsoftJson(options =>
                   {
                       options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                   });

    IGameManager gameManager = new GameManager();

    services.AddTransient<IGameManager>(gm => gameManager);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseCors(options => 
                   options.WithOrigins("https://localhost:44314").AllowAnyMethod());
    app.UseHttpsRedirection();
    app.UseRouting();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
                         { endpoints.MapControllers(); });
}

And the jQuery request:

var data = {
    Name : "Test"
};
$.ajax({
    type: "POST",
    url: "https://localhost:44314/api/test",
    data: data,
    success: (data, status, xhr) => {alert("SUCCESS!")},
    contentType: 'application/json',
    dataType:'json'
  });

I know the url and body are correct, I can see the API reacting by initializing the corresponding controller and I think I get a ACK response for the connection:

火狐网络

But before even entering the Method with the Attribute [HttpGet] Firefox throws the error.

When I do the same request in Postman, everything works just fine, though I could imagine, that postman routes every request through their servers, with would eliminate any CORS problems.

Interestingly I get two errors: (sorry, they are German)

CORS 错误

Alright, so changing the code from

app.UseCors(options =>
   options.WithOrigins("https://localhost:44314").AllowAnyMethod());

to

app.UseCors(
   options => options
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader()
  );

did the trick. Apparently the url I had provided as an exception was not correct (?). I still don't know, WHY my code didn't work, but this is the solution for me. If someone can explain, what I did wrong, please leave a comment, I would like to know!

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