2016-12-01 27 views
19

我已將Azure的ASP.NET Core web API部署到Azure,並且可以使用Swagger或Web調試器(如Fiddler)訪問其端點。在這兩種情況下(在揚鞭相同的起源,使用招從我的電腦不同的產地),訪問API時我得到預期的結果,並啓用CORS在我Startup.cs如下:ASP.NET Core CORS WebAPI:no Access-Control-Allow-Origin標頭

  1. 添加services.AddCors();ConfigureServices

  2. 中間件添加到Configure:我知道,爲了在此事項(ASP.NET 5: Access-Control-Allow-Origin in response),所以我將在方法的頂部這一呼籲,只有通過記錄或診斷中間件之前;這裏是我的全部方法:


public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
    ILoggerFactory loggerFactory, 
    IDatabaseInitializer databaseInitializer) 
{ 
    loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
    loggerFactory.AddDebug(); 
    loggerFactory.AddNLog(); 

    // to serve up index.html 
    app.UseDefaultFiles(); 
    app.UseStaticFiles(); 

    // http://www.talkingdotnet.com/aspnet-core-diagnostics-middleware-error-handling/ 
    app.UseDeveloperExceptionPage(); 
    app.UseDatabaseErrorPage(); 

    // CORS 
    // https://docs.asp.net/en/latest/security/cors.html 
    app.UseCors(builder => 
      builder.WithOrigins("http://localhost:4200", "http://www.myclientserver.com") 
       .AllowAnyHeader() 
       .AllowAnyMethod()); 

    app.UseOAuthValidation(); 
    app.UseOpenIddict(); 
    app.UseMvc(); 

    databaseInitializer.Seed().GetAwaiter().GetResult(); 
    env.ConfigureNLog("nlog.config"); 

    // swagger 
    app.UseSwagger(); 
    app.UseSwaggerUi(); 
} 

localhost CORS開發過程中使用,並指Angular2 CLI應用程序。 CORS在本地工作正常,並且我的客戶端和API應用程序位於同一本地主機上的不同端口上,所以這是「真正的」交叉源(我正在評論這是因爲我在這裏找到的建議:https://weblog.west-wind.com/posts/2016/Sep/26/ASPNET-Core-and-CORS-Gotchas:該帖子的作者注意到響應中的CORS頭部僅在實際需要時才發送,即在真正的跨越原始環境中)。

使用Fiddler我可以成功訪問遠程API,但是我得到了NO Access-Control-Allow-Origin頭。因此,呼籲來自瀏覽器的API(通過我的客戶端應用程序),當AJAX請求失敗,即使服務器返回200樣品提琴手請求(成功):

GET http://mywebapisiteurl/api/values HTTP/1.1 
User-Agent: Fiddler 

響應:

HTTP/1.1 200 OK 
Transfer-Encoding: chunked 
Content-Type: application/json; charset=utf-8 
Server: Microsoft-IIS/8.0 
X-Powered-By: ASP.NET 
Set-Cookie: ARRAffinity=3d551180c72208c1d997584c2b6119cf44e3a55c868f05ffc9258d25a58e95b1;Path=/;Domain=prinapi.azurewebsites.net 
Date: Thu, 01 Dec 2016 10:30:19 GMT 

["value1","value2"] 

當試圖訪問部署在Azure上的遠程API,我的客戶端應用程序總是失敗的AJAX請求錯誤:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.myclientserver.com' is therefore not allowed access. 

下面是使用Angular2(使用Plunker)的樣本客戶機代碼:

import {Component, NgModule} from '@angular/core'; 
import {BrowserModule} from '@angular/platform-browser'; 
import { Http, Headers, Response } from '@angular/http'; 
import { HttpModule } from '@angular/http'; 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h2>Hello {{name}}</h2> 
     <button (click)="test()">test</button> 
    </div> 
    `, 
}) 
export class App { 
    name:string; 
    constructor(private _http: Http) { 
    this.name = 'Angular2' 
    } 
    public test() { 
    this._http.get('http://theapisiteurlhere/api/values', 
    { 
     headers: new Headers({ 
      'Content-Type': 'application/json' 
     }) 
    }) 
    .subscribe(
     (data: any) => { 
     console.log(data); 
     }, 
     error => { 
     console.log(error); 
     }); 
    } 
} 

@NgModule({ 
    imports: [ BrowserModule, HttpModule ], 
    declarations: [ App ], 
    bootstrap: [ App ] 
}) 
export class AppModule {} 

綜上所述,似乎ASPNET API服務器未返回預期的CORS頭,因而我的基於瀏覽器的客戶端託管在不同的產地失敗。然而,CORS的設置似乎沒有問題,至少從上面引用的文件來看,我處於真正的跨源性環境中;我將中間件放在其他人面前。也許我錯過了一些明顯的東西,但圍繞這些都是我找到的所有建議。任何提示?

UPDATE

在答覆@Daniel JG:從提琴手請求/響應是成功的:

GET http://theapiserver/api/values HTTP/1.1 
User-Agent: Fiddler 
Host: theapiserver 
Origin: http://theappserver/apps/prin 

和:從Angular2

HTTP/1.1 200 OK 
Content-Type: application/json; charset=utf-8 
Server: Microsoft-IIS/8.0 
Access-Control-Allow-Origin: http://theappserver/apps/prin 
X-Powered-By: ASP.NET 
Set-Cookie: ARRAffinity=3d551180c72208c1d997584c2b6119cf44e3a55c868f05ffc9258d25a58e95b1;Path=/;Domain=theapiserver 
Date: Thu, 01 Dec 2016 14:15:21 GMT 
Content-Length: 19 

["value1","value2"] 

的請求/響應(據報道,Plunker)失敗了。通過檢查網絡流量,我只能看到預檢要求:

OPTIONS http://theapiserver/api/values HTTP/1.1 
Host: theapiserver 
Proxy-Connection: keep-alive 
Access-Control-Request-Method: GET 
Origin: http://run.plnkr.co 
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36 
Access-Control-Request-Headers: content-type 
Accept: */* 
Referer: http://run.plnkr.co/h17wYofXGFuTy2Oh/ 
Accept-Encoding: gzip, deflate, sdch 
Accept-Language: en-US,en;q=0.8,it;q=0.6 

HTTP/1.1 204 No Content 
Server: Microsoft-IIS/8.0 
X-Powered-By: ASP.NET 
Set-Cookie: ARRAffinity=3d551180c72208c1d997584c2b6119cf44e3a55c868f05ffc9258d25a58e95b1;Path=/;Domain=theapiserver 
Date: Thu, 01 Dec 2016 14:23:02 GMT 

在此之後,則請求失敗,沒有更多的流量轉到服務器。所報告的問題是,Response to preflight request doesn't pass access control check,又由於缺乏在響應中的頭信息:

XMLHttpRequest cannot load http://theapiserver/api/values. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://run.plnkr.co' is therefore not allowed access. 
+0

有你在小提琴手嘗試設置主機和起源頭(主機到主機的API和起源於一個不同的模擬跨原點)?如果您發佈由角度製作的rquest的細節,它也可能有所幫助。 –

+0

謝謝,我更新了我的帖子(請參閱底部)。總之,使用Fiddler是沒問題的;使用Angular2,儘管CORS被啓用,但是預檢請求失敗,因爲服務器響應中沒有ACAO頭。 – Naftis

+0

您確定原始的'http:// run.plnkr.co'是允許的起源之一嗎? –

回答

3

添加.AllowAnyOrigin()方法能夠解決您的問題

app.UseCors(builder => 
     builder.WithOrigins("http://localhost:4200", "http://www.myclientserver.com") 
      .AllowAnyOrigin() 
      .AllowAnyHeader() 
      .AllowAnyMethod()); 
+0

這個想法是不允許任何orgin,所以我不明白這個答案的重點? –

+0

不.AllowAnyOrigin()只允許任何來源? – Axelle

0

的WebAPI項目--->右鍵在Manage Nuget Packages部分單擊References ---> Search Core。通過安裝將Microsoft.AspNet.WebApi.Cors添加到項目中

將以下代碼添加到項目中App_Start文件夾下的WebApi.Config文件中。

var cors = new EnableCorsAttribute(「」,「」,「*」); config.EnableCors(cors);

enter image description here

enter image description here

+0

OP在詢問ASP.NET CORE,而不是ASP.NET – ews2001