当angularjs向web api发出post请求时出现错误405

时间:2014-10-09 14:54:10

标签: angularjs cors asp.net-web-api

我在IIS上托管了Web Api服务(localhost:81),我在IIS Express上运行的angularjs应用程序(localhost:8080)正在尝试与之通信。

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>

此外,我可以发出GET请求,但遇到了POST请求的问题。

Fiddler的详细信息是:

 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

我尝试直接从Fiddler提出请求,这导致了成功

 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"}

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

我设法通过向WebApiConfig.Register方法添加以下内容来修复它

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

从Web.config和Startup.cs中删除了CORS配置