簡體   English   中英

無法使CORS適用於ASP.NET Core Web API

[英]Can't get CORS working for ASP.NET Core Web API

我有兩個本地運行的應用程序。 一個是提供JSON響應的ASP.NET Core Web API( http:// localhost:8081 )。 另一個是調用API的Javascript應用程序( http:// localhost:8080 )。 我正在測試的API端點是一個POST請求,我已經向Fiddler確認此端點正在運行。

當我從Chrome中的Javascript應用程序發出POST請求時,我看到此錯誤:

無法加載http:// localhost:8081 / api / search :對預檢請求的響應未通過訪問控制檢查:請求的資源上沒有“Access-Control-Allow-Origin”標頭。 因此,不允許來源“ http:// localhost:8080 ”訪問。

但是,這是我的API Startup的全部內容:

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

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvcCore()
        .AddJsonFormatters()
        .AddCors(options =>
        {
            options.AddPolicy("DefaultCorsPolicy",
                builder => builder
                    .WithOrigins("http://localhost:8080")
                    .AllowAnyMethod());
        });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseCors("DefaultCorsPolicy");

    app.UseMvc();
}

我跟着微軟的文檔 ,所以我不確定我錯過了什么。

以下是我在Fiddler中從此端點獲得的原始響應:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Kestrel
X-Powered-By: ASP.NET
Date: Sat, 10 Mar 2018 09:23:46 GMT
Content-Length: 37

[{"id":1,"name":"lorem ipsum dolor"}]

如您所見,不存在Access-Control-Allow-Origin標頭。

您可以嘗試在services.UseCors()調用中配置CORS選項,而不是services.AddCors()。

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddMvcCore();
    ...
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors(builder => builder
        .WithOrigins("http://localhost:8000")
        .AllowAnyHeader()
        .AllowAnyMethod()
    );

    app.UseMvcCore();
    ...
}

注意:通過清除客戶端緩存(如果有)來測試它。 在Chrome> F12>網絡標簽>勾選禁用緩存復選框>刷新頁面。

暫無
暫無

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

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