對預檢的響應:儘管啟用了 CORS,但“沒有 ‘Access-Control-Allowed-Origin’”
我無法解決 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> <!--<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=\"Web\" /optionInfer+" /> </compilers> </system.codedom> </configuration>
我已經設法重現您的問題。對我有用的解決方案是替換部分
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>如果您已經擁有該確切內容,請嘗試刪除它,執行伺服器,停止伺服器,重新添加內容,然後再次執行伺服器。我知道這聽起來很奇怪,但我認為這最終為我解決了問題。祝你好運。
更新#1
現在我們在伺服器端發生了一些事情,請嘗試刪除 Angular 程式碼中的
Content-Type標頭和JSON.stringify內容。IE: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) }更新#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 } ); } }

