简体   繁体   English

JQuery Post to ASP.NET 核心导致CORS错误

[英]JQuery Post to ASP.NET Core results in CORS error

I have an ASP.NET Core API and a html-css-js client side.我有一个 ASP.NET Core API 和一个 html-css-js 客户端。 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.我尝试向 API 发送 post 请求,但 Firefox 抛出同源策略禁止读取外部资源的错误。

The Startup.cs looks like this: Startup.cs看起来像这样:

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:和 jQuery 请求:

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:我知道 url 和 body 是正确的,我可以看到 API 通过初始化相应的 controller 做出反应,我想我得到了连接的 ACK 响应:

火狐网络

But before even entering the Method with the Attribute [HttpGet] Firefox throws the error.但是在使用属性 [HttpGet] Firefox 进入方法之前会抛出错误。

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.当我在 Postman 中执行相同的请求时,一切正常,尽管我可以想象,postman 通过他们的服务器路由每个请求,将消除任何 CORS 问题。

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 (?).显然我作为例外提供的 url 不正确(?)。 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!如果有人可以解释,我做错了什么,请发表评论,我想知道!

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

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