6

CORSのアクセス制御チェックをパスしない角度4のプリフライトリクエストで問題が発生しました。 -Control-Allowed-Origin '」を参照してください。私は正常にdbからデータを取得することはできますが、データを投稿/保存することはできません。ビジュアルスタジオ2015のバックエンドにアクセスするためにフロントエンドにVSコードを使用しています。私のWeb APIをコントローラがの属性があります。CORSが有効であるにもかかわらず、プリフライトへの応答:「アクセス制御が許可されたアクセスポイントがありません」

[EnableCors(origins: "*", headers: "*", methods: "*")]

[HttpPost] 
    public async Task<IHttpActionResult> Post([FromBody]Employee employee) 
    { 
     _repo.Create(employee); 
     return Ok(); 
    } 

を...しかし、要求が行われたときに、私はのエラーを取得しています:

のXMLHttpRequestがhttp://localhost:54429/api/createEmployee/をロードすることはできません。 プリフライト要求への応答がアクセス制御チェックを通過しません。いいえ 要求された リソースに 'Access-Control-Allow-Origin'ヘッダーが存在します。ポストから、本体とオプションを除去した後

postEmployeeForm(employee: Employee): Observable<any>{ 

    let body = JSON.stringify(employee); 
    let headers = new Headers(); 
    headers.append('Content-Type', 'application/json'); 
    let options  = new RequestOptions({ headers: headers }); 

    console.log('posting employee ' , employee); 

    return this.http.post("http://localhost:54429/api/employees/", body, options) 
        .map(this.extractData) 
        .catch(this.handleError) 


} 

enter image description here

405応答:起源「http://localhost:4200」がゆえ私のVSのコードでは アクセス

を許可されていない、私のサービスは、このようになります。 。

enter image description here

ない私が行方不明です何を確認してください。

Web構成

<configuration> 
    <configSections> 
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> 
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> 
    </configSections> 
    <connectionStrings> 
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-TBryant.WebAPI-20170303082842.mdf;Initial Catalog=aspnet-TBryant.WebAPI-20170303082842;Integrated Security=True" providerName="System.Data.SqlClient" /> 
    <!--<add name="SampleEntities" connectionString="metadata=res://*/MyModels.csdl|res://*/MyModels.ssdl|res://*/MyModels.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(localdb)\MSSQLLocalDB;initial catalog=Sample;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />--> 
    <add name="northwindEntities" connectionString="metadata=res://*/NorthwindModel.csdl|res://*/NorthwindModel.ssdl|res://*/NorthwindModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(localdb)\MSSQLLocalDB;initial catalog=northwind;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> 
    <add name="SampleEntities1" connectionString="metadata=res://*/EmployeeDataModel.csdl|res://*/EmployeeDataModel.ssdl|res://*/EmployeeDataModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(localdb)\MSSQLLocalDB;initial catalog=Sample;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> 
    </connectionStrings> 
    <appSettings></appSettings> 
    <system.web> 
    <authentication mode="None" /> 
    <compilation debug="true" targetFramework="4.6.1" /> 
    <httpRuntime targetFramework="4.6.1" /> 
    </system.web> 
    <system.webServer> 
    <!--<httpProtocol> 
     <customHeaders> 
     <add name="Access-Control-Allow-Origin" value="*"/> 
     <add name="Access-Control-Allow-Headers" value="Content-Type"/> 
     <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELTE,OPTIONS"/> 
     </customHeaders> 
    </httpProtocol>--> 
    <modules> 
     <remove name="FormsAuthentication" /> 
    </modules> 
    <handlers> 
     <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> 
     <remove name="OPTIONSVerbHandler" /> 
     <remove name="TRACEVerbHandler" /> 
     <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> 
    </handlers> 
    </system.webServer> 
    <runtime> 
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> 
     <dependentAssembly> 
     <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" /> 
     <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> 
     </dependentAssembly> 
     <dependentAssembly> 
     <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" /> 
     <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> 
     </dependentAssembly> 
     <dependentAssembly> 
     <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" /> 
     <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> 
     </dependentAssembly> 
     <dependentAssembly> 
     <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" /> 
     <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> 
     </dependentAssembly> 
     <dependentAssembly> 
     <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" /> 
     <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" /> 
     </dependentAssembly> 
     <dependentAssembly> 
     <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" /> 
     <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" /> 
     </dependentAssembly> 
     <dependentAssembly> 
     <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /> 
     <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" /> 
     </dependentAssembly> 
     <dependentAssembly> 
     <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /> 
     <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> 
     </dependentAssembly> 
     <dependentAssembly> 
     <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> 
     <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" /> 
     </dependentAssembly> 
     <dependentAssembly> 
     <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /> 
     <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> 
     </dependentAssembly> 
     <dependentAssembly> 
     <assemblyIdentity name="System.Web.Cors" publicKeyToken="31bf3856ad364e35" culture="neutral" /> 
     <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" /> 
     </dependentAssembly> 
    </assemblyBinding> 
    </runtime> 
    <entityFramework> 
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> 
    <providers> 
     <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> 
    </providers> 
    </entityFramework> 
    <system.codedom> 
    <compilers> 
     <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" /> 
     <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" /> 
    </compilers> 
    </system.codedom> 
</configuration> 
+0

ワイルドカード(*)ではない特定のヘッダーとメソッドを宣言しようとします。 –

+0

@JesusCarrasco当初は特定のローカルホストURLを持っていたものの、ワイルドカードにオープンしていたので、それはワイルドカードになりました –

+0

@TroyBryant、WebDAVモジュールを削除しようとしました。サーバーはget、post要求のみをサポートします。 ref-link:https://weblog.west-wind.com/posts/2015/apr/09/aspnet-mvc-httpverbsdeleteput-routes-not-firing#AdditionalIssues:WebDav –

答えて

3

問題を再現できました。私のために働いた解決策はWeb.configの一部を置き換えることです。 system.webServerの下では、追加または置換既存<handlers>ブロックを、次のいずれか:

<handlers> 
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> 
    <remove name="OPTIONSVerbHandler" /> 
    <remove name="TRACEVerbHandler" /> 
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> 
</handlers> 

すでに場所でその正確な内容を持っている場合は、サーバを実行して、それを削除してみてください、サーバーを停止し、コンテンツを再追加し、もう一度サーバーを実行してください。私はそれが奇妙に聞こえることを知っていますが、私はそれが私のためにそれを修正し終えたと思いますがんばろう。

UPDATE#1

今、私たちは物事のサーバー側で起こって何かを持っていることを、あなたの角度コードでContent-TypeヘッダーとJSON.stringifyものを削除してみてください。すなわち:

postEmployeeForm(employee: Employee): Observable<any>{ 
    console.log('posting employee ' , employee); 

    return this.http.post("http://localhost:54429/api/employees/", employee) 
     .map(this.extractData) 
     .catch(this.handleError) 
} 

UPDATE#2

私はあなたのIIS Expressの設定は、我々が行った変更の一部をオーバーライドすることができると思います。 Visual Studioを終了し、Windowsエクスプローラでソリューションのルートにある.vs/configフォルダを削除してから、プロジェクトを再実行してください。これにより、IIS Expressの設定がリセットされます。フォルダを完全に削除できない場合は、名前を変更して同じプロセスに従ってください。

UPDATE#3

私はあなたの例のプロジェクトの実行を得ることができました。これは、CORSに問題があることを示しているが、これはconfig.EnableCorsを追加することの私の最初の提案を使用することによって修正されました:

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
     // Web API configuration and services 
     config.EnableCors(); 

     // Web API routes 
     config.MapHttpAttributeRoutes(); 

     config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 
    } 
} 
+0

元々は、このコメントアウトがありました。私は、そのセクションのコメントを外したという記事を見ました。今度は私のエラーです。プリフライトのレスポンスは無効なHTTPステータスコード405を持っています。 –

+0

405レスポンスメソッドが許可されていません。 –

+0

は上記の単純なポストメソッド –

2

問題は、サーバー側であるように思われます。

non-simple CORS requestの前に、ブラウザはOPTIONSプリフライトリクエストを送信して、このサーバーが単純ではないCORSリクエストを許可していることを確認します。 (application/jsonのPOST要求は単純ではありません)

エラーが示すように、プリフライトOPTIONS要求への応答に値が 'http://localhost:4200'のアクセス制御許可元ヘッダーが含まれている場合にのみ、元のPOST要求が送信されます。

あなたはサーバの実装について書きませんでしたが、ここでasp.net-web-apiを使用している場合は、それを作る方法に関する簡単な(ちょっとハッキリな)解決策がありますこれらのプリフライトOPTIONSリクエストに応答する - link (Also see the comment there by Marcus Cunningham)

関連する問題