2017-05-09 44 views
-1

我有WEBAPI項目和AngularJS客戶端項目。 $ http.get調用工作正常,$ http.post調用與空數據正在工作,但數據拋出錯誤「405(方法不允許)」。我也啓用CORS。請提供解決方案。

我已經加入以下的事情web.config中

<handlers> 
     <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> 
     <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /> 
     <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /> 
    <remove name="OPTIONSVerbHandler" /> 
     <remove name="TRACEVerbHandler" /> 

     <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS,XYZ" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" /> 
     <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS,XYZ" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" /> 
     <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> 
    </handlers> 



<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, DELETE, OPTIONS" /> 
    </customHeaders> 
</httpProtocol> 

這是的WebAPI

[HttpPost] 公共BOOL SubmitQuesiton(JObject數據) { 返回Factory.SubmitQuestion(數據); }

這是AngularJS代碼

data = JSON.stringify(data); 
     $http({ 
      method: 'POST', 
      url: "http://localhost:53546/api/demo/SubmitQuesiton", 
      headers: { 
       'Content-Type': 'application/json', 
       'Accept': 'application/json' 
      }, 
      data: data 
     }) 
+0

請檢查網絡。根據「asp.net-web-api」,這個問題有幾十個答案。 – lin

+0

@lin嘗試了幾個小時的搜索,但無法解決問題 – Speedy

+0

因此,除了增加您的問題之外,您現在已經嘗試過了。 – lin

回答

0

回答自己的問題。問題是由於CORS,它應該在WEBAPI項目中啓用。 CORS啓用不能通過WEB.config代碼工作,您需要通過後端啓用CORS。

注 - 刪除所有的web.config CORS實現代碼,如果它的存在,在web.config中即下面的代碼

<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, DELETE, OPTIONS" /> 
    </customHeaders> 
</httpProtocol> 

步驟 1.安裝CORS包安裝,包Microsoft.AspNet.WebApi.Cors爲的WebAPI項目 2.在WebApiConfig.cs添加以下代碼

var corsAttribute = new EnableCorsAttribute("*","Origin, Content-Type, Accept", 
               "GET, PUT, POST, DELETE, OPTIONS"); 
      config.EnableCors(corsAttribute); 

完成。