2016-04-17 47 views
0

即使我在我的控制器中啓用了CORS,但我卻遇到了這個錯誤。 無法加載資源:服務器與405狀態響應(不允許的方法)ASP.Net:CORS錯誤:無法加載資源:服務器響應狀態爲405(方法不允許)

我想表單數據後,通過Ajax調用的控制器。

var data = $.param({ 
     emailId: $scope.txtEmailAddr, 
     passwd: $scope.txtPswd 
    }); 
    var config = { 
     headers: { 
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' 
     } 
    } 

$http.post('../api/login/1', data) 
     .success(function (data, status, headers, config) { 
      alert("Success" + data); 
      $state.go('app.dashboard.v2'); 

     }) 
     .error(function (data, status, header, config) { 
      alert("Error"); 

     }); 

這是打在瀏覽器的網址: http://localhost:27622/template_content_angularjs/index.html#/member/login/v2 這個頁面有一個提交按鈕和點擊它,它會調用Ajax調用並在內部嘗試調用控制器API。這給出了上述錯誤。

當我通過瀏覽器調用我的控制器,它運行成功如下返回數據: 控制器通過URL瀏覽器調用:由控制器返回http://localhost:27622/api/login/1

數據。

<Login xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/kindergarten.template_content_angularjs.Models"> 
<Password>[email protected]</Password> 
<UserName>Adnan1</UserName> 
<id>1</id> 
</Login> 

這是控制器代碼。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Net.Http; 
using System.Web.Http; 
using kindergarten.template_content_angularjs.Models; 

using System.Web.Http.Cors; 

namespace kindergarten.template_content_angularjs.controllers 
{ 
    [EnableCors(origins: " http://localhost:27622", headers: "*", methods: "*")] 
    public class LoginController : ApiController 
    { 
     Login[] ArrLogin = new Login[] 
    { 
      new Login { id=1, UserName = "Adnan1", Password = "[email protected]" }, 
      new Login { id=2, UserName = "Adnan2", Password = "[email protected]" }, 
      new Login { id=3, UserName = "Adnan3", Password = "[email protected]" } 
     }; 

     public IEnumerable<Login> GetAllLogins() 
     { 
      return ArrLogin; 
     } 

     public IHttpActionResult GetLogin(int id) 
     { 
      var product = ArrLogin.FirstOrDefault((p) => p.id == id); 
      if (product == null) 
      { 
       return NotFound(); 
      } 
      return Ok(product); 
     } 
    } 
} 

我已經通過CORS閱讀,但仍然無法理解,雖然我打電話給同一臺服務器,但我得到了上述錯誤。另外我在控制器中啓用了CORS。

+0

從地址欄加載url時,瀏覽器使用GET **方法**,但您的ajax請求發出POST **方法**請求。錯誤消息說,無法加載資源:服務器響應狀態爲405(**方法**不允許) – Musa

+0

@Musa的解決方案是什麼? –

回答

1

@Musa雖然說ajax請求是POST方法的正確的事情。問題出在我的控制器上,我沒有處理POST方法。 解決方案是

public string Post([FromBody] string value) 
{ 
    return value; 
} 

處理post方法。控制器中沒有用於處理POST方法的API。它只處理Get方法。

對不起人們的麻煩。希望這可以幫助像我這樣的其他新手。

相關問題