2014-10-09 104 views
0

我在IIS(localhost:81)上託管Web Api服務,並且我在IIS Express上運行的angularjs應用程序(localhost:8080)試圖與它通信。當angularjs向web api發出post請求時出現錯誤405

的angularjs服務功能如下

function Register(username, password) { 
    var data = { "username": username, "password": password }; 
    var promise = $http.post('http://localhost:81/api/Account', JSON.stringify(data)); 
    return promise; 
} 

我的Web API服務方法看起來像

public class AccountController : ApiController 
{ 
    [HttpPost] 
    public bool Post(User user) 
    { 
     Core.DataContracts.AuthenticationResponse authResponse = Account.CreateUser(Mapper.Map<Core.DataContracts.User>(user)); 
     return (authResponse.Code == Core.DataContracts.ResponseCode.Created); 
    } 
} 

我讀了各種論壇,這可能是與CORS做的,但我有Access-Control-Allow-Origin在我的web.config

<httpProtocol> 
    <customHeaders> 
    <add name="Access-Control-Allow-Origin" value="*" /> 
    </customHeaders> 
</httpProtocol> 

另外,我是abl e發出GET請求,但是POST請求存在此問題。從提琴手

詳情如下:

OPTIONS http://localhost:81/api/Account HTTP/1.1 
Host: localhost:81 
Connection: keep-alive 
Access-Control-Request-Method: POST 
Origin: http://localhost:8080 
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.101 Safari/537.36 
Access-Control-Request-Headers: accept, content-type 
Accept: */* 
Referer: http://localhost:8080/app/index.html 
Accept-Encoding: gzip,deflate,sdch 
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6 

我試圖使直接從提琴手請求導致成功

POST http://localhost:81/api/Account HTTP/1.1 
User-Agent: Fiddler 
Host: localhost:81 
Content-Length: 40 
Content-Type: application/json 

{"username":"abc","password":"asasasas"} 

任何幫助,將不勝感激。

+0

你確定你的郵寄地址是正確的? HTTP 405意味着該方法不被允許。 – GeoffreyB 2014-10-09 14:55:18

+0

@GeoffreyB查看我通過Fiddler直接提出的請求,地址相同,但結果是成功。 – Junaid 2014-10-09 15:03:52

回答

0

我設法通過增加來解決它下面來WebApiConfig.Register方法

var cors = new EnableCorsAttribute("*", "*", "*"); 
config.EnableCors(cors); 

而且從Web.config文件和Startup.cs

去除CORS配置
相關問題