【发布时间】:2017-04-23 01:21:07
【问题描述】:
我正在尝试在一个测试学习者项目中让 angular 2 与 web api 一起使用,但我遇到了一个关于 http.put 的问题,想知道是否有人可以对此有所了解。
我可以 POST 一个对象到 web api,我可以从中获取数据。
我在使用 Chrome 时遇到了 PUT 问题。我说使用 Chrome 的原因是它在 Chrome 中不起作用,但在 IE 中起作用 - 你不经常这么说;)
我使用的 angular 2 方法是这样的。如果我用 POST 替换 PUT,我可以在我的 web api 控制器中打断点,但使用 PUT 不行。
updateUser(user: UserModel) {
let body = JSON.stringify(user);
let headers = new Headers({ 'Content-Type': 'application/json' });
let url: string = 'http://localhost:57465/api/user';
this.http.put(url, body, { headers: headers })
.map((res: Response) => res.json())
.subscribe((res2) => {
console.log('subscribed');
});
}
我在使用 put 时出现的控制台 Chrome 错误消息:
XMLHttpRequest cannot load http://localhost:57465/api/user. Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
EXCEPTION: Response with status: 0 for URL: null
Web api 方法是开箱即用的。我还没有和他们做任何事情。如果我在 POST 上设置一个断点,它会被击中,而不是 PUT。
// POST api/user
public void Post(User user)
{
}
// PUT api/user/5
public void Put(User user)
{
}
Web api 访问控制方法正在 Global.asax 中设置
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Request-Method", "GET ,POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Origin,Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "86400"); // 24 hours
HttpContext.Current.Response.End();
}
}
难道不应该像对 POST 一样对 PUT 起作用吗?它是如何在 IE 中运行的?
有什么想法吗?
【问题讨论】:
标签: angular asp.net-web-api cors asp.net-web-api2