2016-12-01 9 views
19

ASP.NETコアWeb APIをAzureにデプロイしました。SwaggerやFiddlerのようなWebデバッガを使用してエンドポイントにアクセスできます。ASP.NET Core CORS WebAPI:Access Control-Allow-Originヘッダーなし

  1. ConfigureServicesservices.AddCors();を追加:APIにアクセスするときに、両方のケース(SWAGGERで同じ起源、異なる起源の私のコンピュータからバイオリンを使用して)で、私は私のStartup.csに次のように有効にCORSで、期待される結果を取得します。

  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:実際に必要な場合、つまり実際のクロスオリジン環境では、 のみが送信されます。

Fiddlerを使用すると、リモートAPIに正常にアクセスできますが、私はAccess-Control-Allow-Originヘッダーを取得します。

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"] 

(私のクライアントアプリケーションを介して)ブラウザからAPIを呼び出すときにこのように、AJAX要求は、サーバーが200サンプルフィドラー要求(成功)を返した場合でも、失敗しました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. 

は(Plunkerを使用して)Angular2を使用してサンプルクライアントコードです:

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 

を、要求が失敗し、より多くのトラフィックをサーバに行きません。

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ホストと原点にホストを)試したことがありますか?あなたが角度から作られた格言の詳細を投稿すると、それはまた助けになるかもしれません。 –

+0

ありがとうございました、私は自分の投稿を更新しました(下部を参照)。要するに、Fiddlerを使用しても問題ありません。 Angular2を使用すると、CORSが有効になっているにもかかわらず、サーバー応答にACAOヘッダーがないため、プリフライト要求が失敗します。 – Naftis

+0

原点 'http:// run.plnkr.co'は許可された起点の1つですか? –

答えて

3

.AllowAnyOrigin()メソッドあなたの問題

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

アイデアはどのorginも許可しないので、私はその答えのポイントを理解していませんか? –

+0

'.AllowAnyOrigin()'は起点を許可していませんか? – Axelle

0

WEBAPIプロジェクトを修正する可能性が--->右の追加:報告された問題が再びため、応答のヘッダの欠如のResponse to preflight request doesn't pass access control checkが、ということです「参照」--->「ナゲットパッケージの管理」の「コアを検索」をクリックします。

プロジェクト内のApp_Startフォルダの下にあるWebApi.Configファイルに次のコードを追加してください:Microsoft.AspNet.WebApi.Corsをプロジェクトに追加します。

var cors = new EnableCorsAttribute( ""、 ""、 "*"); config.EnableCors(cors);

enter image description here

enter image description here

+0

OPはASP.NETではなくASP.NET COREについて質問しています – ews2001

関連する問題