当angularjs向web api发出post请求时出现错误405
问题描述:
我在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"}
任何帮助,将不胜感激。
答
我设法通过增加来解决它下面来WebApiConfig.Register方法
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
而且从Web.config文件和Startup.cs
去除CORS配置
你确定你的邮寄地址是正确的? HTTP 405意味着该方法不被允许。 – GeoffreyB 2014-10-09 14:55:18
@GeoffreyB查看我通过Fiddler直接提出的请求,地址相同,但结果是成功。 – Junaid 2014-10-09 15:03:52