簡體   English   中英

JQuery Post to ASP.NET 核心導致CORS錯誤

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

我有一個 ASP.NET Core API 和一個 html-css-js 客戶端。 我嘗試向 API 發送 post 請求,但 Firefox 拋出同源策略禁止讀取外部資源的錯誤。

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

和 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'
  });

我知道 url 和 body 是正確的,我可以看到 API 通過初始化相應的 controller 做出反應,我想我得到了連接的 ACK 響應:

火狐網絡

但是在使用屬性 [HttpGet] Firefox 進入方法之前會拋出錯誤。

當我在 Postman 中執行相同的請求時,一切正常,盡管我可以想象,postman 通過他們的服務器路由每個請求,將消除任何 CORS 問題。

有趣的是我得到兩個錯誤:(對不起,他們是德國人)

CORS 錯誤

好吧,所以改變代碼從

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

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

成功了。 顯然我作為例外提供的 url 不正確(?)。 我仍然不知道,為什么我的代碼不起作用,但這是我的解決方案。 如果有人可以解釋,我做錯了什么,請發表評論,我想知道!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM