6

我無法找出未通過CORS訪問控制檢查的角度4預檢請求的問題:「否」訪問 - 控制允許的原產地」。我能夠成功從數據庫獲取數據,但無法發佈/保存數據。我在我的前端使用VS代碼來訪問我的visual studio 2015後端。我的網絡API控制器具有的屬性:對印前檢查的響應:「No'Access-Control-Allowed-Origin'」儘管啓用了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/。 對預檢請求的響應未通過訪問控制檢查:否 請求的 資源上存在「訪問控制 - 允許來源」標頭。原產地「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) 


} 

enter image description here

405響應。

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原來這就是我有特定的本地主機的網址,但那不工作,所以我打開它通配符 –

+0

@TroyBryant,嘗試刪除webDAV模塊,如果它被添加到您的網站或服務器和您的迴應只是定義服務器只支持獲取,發佈請求。 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> 

如果你已經有到位確切的內容,請嘗試刪除它,運行服務器,停止服務器,重新添加的內容和然後再次運行服務器。我知道這聽起來很奇怪,但我認爲這是爲我修復它的結果。祝你好運。

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

更新#2

我覺得你的IIS Express配置可能會改寫一些我們所做的更改。關閉Visual Studio,刪除Windows資源管理器中解決方案根目錄下的.vs/config文件夾,然後嘗試重新運行該項目。這應該重置您的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 } 
     ); 
    } 
} 
+0

本來我有這個評論。我確實看到一篇文章說,取消註釋該部分。現在我的錯誤是響應的預檢有無效的HTTP狀態代碼405. –

+0

405響應方法不允許添加上面的圖像 –

+0

添加上面的簡單後處理方法 –

2

這個問題似乎是在服務器端。

在任何non-simple CORS request之前,瀏覽器發送OPTIONS預檢請求以確保此服務器允許非簡單的CORS請求。 (與應用程序/ JSON POST請求不被認爲是簡單的)

在你的情況下,作爲錯誤意味着,只有當到預檢OPTIONS請求響應中包含具有值「http://localhost:4200」的訪問控制允許來源頭您的原始POST請求將被髮送。 (屏幕截圖中的響應不包含此標頭)

你沒有寫太多關於你的服務器實現,但如果你使用asp.net-web-api這裏是一個簡單的(有點哈克)解決方案,如何使它響應這些預檢選項請求 - link (Also see the comment there by Marcus Cunningham)

相關問題