Asp.net-Web-Api

對預檢的響應:儘管啟用了 CORS,但“沒有 ‘Access-Control-Allowed-Origin’”

  • June 8, 2018

我無法解決 Angular 4 預檢請求未通過 CORS 訪問控制檢查的問題:“No ‘Access-Control-Allowed-Origin’”。我能夠成功地從數據庫中獲取數據,但無法發布/保存數據。我在前端使用 VS 程式碼來訪問我的 Visual Studio 2015 後端。我的 Web Api 控制器具有以下屬性:

[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”標頭。因此不允許訪問源“ http://localhost:4200 ”

在我的 vs 程式碼中,我的服務如下所示:

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)


}

在此處輸入圖像描述

從文章中刪除正文和選項後的 405 響應。

在此處輸入圖像描述

不知道我錯過了什麼。

網路配置

<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="data source=(localdb)\MSSQLLocalDB;initial catalog=Sample;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" 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="data source=(localdb)\MSSQLLocalDB;initial catalog=northwind;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" 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="data source=(localdb)\MSSQLLocalDB;initial catalog=Sample;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" 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>
   &lt;!--<httpProtocol>
     &lt;customHeaders&gt;
       &lt;add name="Access-Control-Allow-Origin" value="*"/&gt;
       &lt;add name="Access-Control-Allow-Headers" value="Content-Type"/&gt;
       &lt;add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELTE,OPTIONS"/&gt;
     &lt;/customHeaders&gt;
   &lt;/httpProtocol&gt;--&gt;
   &lt;modules&gt;
     &lt;remove name="FormsAuthentication" /&gt;
   &lt;/modules&gt;
   &lt;handlers&gt;
     &lt;remove name="ExtensionlessUrlHandler-Integrated-4.0" /&gt;
     &lt;remove name="OPTIONSVerbHandler" /&gt;
     &lt;remove name="TRACEVerbHandler" /&gt;
     &lt;add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /&gt;
   &lt;/handlers&gt;
 &lt;/system.webServer&gt;
 &lt;runtime&gt;
   &lt;assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"&gt;
     &lt;dependentAssembly&gt;
       &lt;assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" /&gt;
       &lt;bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /&gt;
     &lt;/dependentAssembly&gt;
     &lt;dependentAssembly&gt;
       &lt;assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" /&gt;
       &lt;bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /&gt;
     &lt;/dependentAssembly&gt;
     &lt;dependentAssembly&gt;
       &lt;assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" /&gt;
       &lt;bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /&gt;
     &lt;/dependentAssembly&gt;
     &lt;dependentAssembly&gt;
       &lt;assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" /&gt;
       &lt;bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /&gt;
     &lt;/dependentAssembly&gt;
     &lt;dependentAssembly&gt;
       &lt;assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" /&gt;
       &lt;bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" /&gt;
     &lt;/dependentAssembly&gt;
     &lt;dependentAssembly&gt;
       &lt;assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" /&gt;
       &lt;bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" /&gt;
     &lt;/dependentAssembly&gt;
     &lt;dependentAssembly&gt;
       &lt;assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /&gt;
       &lt;bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" /&gt;
     &lt;/dependentAssembly&gt;
     &lt;dependentAssembly&gt;
       &lt;assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /&gt;
       &lt;bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /&gt;
     &lt;/dependentAssembly&gt;
     &lt;dependentAssembly&gt;
       &lt;assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /&gt;
       &lt;bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" /&gt;
     &lt;/dependentAssembly&gt;
     &lt;dependentAssembly&gt;
       &lt;assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /&gt;
       &lt;bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /&gt;
     &lt;/dependentAssembly&gt;
     &lt;dependentAssembly&gt;
       &lt;assemblyIdentity name="System.Web.Cors" publicKeyToken="31bf3856ad364e35" culture="neutral" /&gt;
       &lt;bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" /&gt;
     &lt;/dependentAssembly&gt;
   &lt;/assemblyBinding&gt;
 &lt;/runtime&gt;
 &lt;entityFramework&gt;
   &lt;defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /&gt;
   &lt;providers&gt;
     &lt;provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /&gt;
   &lt;/providers&gt;
 &lt;/entityFramework&gt;
 &lt;system.codedom&gt;
   &lt;compilers&gt;
     &lt;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" /&gt;
     &lt;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+" /&gt;
   &lt;/compilers&gt;
 &lt;/system.codedom&gt;
&lt;/configuration&gt;

我已經設法重現您的問題。對我有用的解決方案是替換部分Web.config. 在 下system.webServer,使用以下內容添加或替換現有&lt;handlers&gt;塊:

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

如果您已經擁有該確切內容,請嘗試刪除它,執行伺服器,停止伺服器,重新添加內容,然後再次執行伺服器。我知道這聽起來很奇怪,但我認為這最終為我解決了問題。祝你好運。

更新#1

現在我們在伺服器端發生了一些事情,請嘗試刪除 Angular 程式碼中的Content-Type標頭和JSON.stringify內容。IE:

postEmployeeForm(employee: Employee): Observable&lt;any&gt;{
   console.log('posting employee ' , employee);

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

更新#2

我認為您的 IIS Express 配置可能會覆蓋我們所做的一些更改。關閉 Visual Studio,.vs/config在 Windows 資源管理器中刪除解決方案根目錄下的文件夾,然後嘗試重新執行該項目。這應該重置您的 IIS Express 設置。如果您對刪除文件夾不滿意,只需重命名它並按照相同的過程進行操作。

更新#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 }
       );
   }
}

引用自:https://stackoverflow.com/questions/46249767