【问题标题】:http.put throwing error in Angular 2 / Web API using Chrome but not IEhttp.put 在使用 Chrome 但不是 IE 的 Angular 2 / Web API 中抛出错误
【发布时间】: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


    【解决方案1】:

    好的,我得到了这个工作。 angular2侧很好。 Web API 需要修改。

    我把 BeginRequest 改成了这个

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
            {
                Response.Flush();
            }
        }
    

    将 CustomHeaders 放回 web.config

      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
      </customHeaders>
    

    就是这样。

    【讨论】:

      猜你喜欢
      • 2015-09-25
      • 2020-11-24
      • 2018-03-10
      • 2018-03-26
      • 2021-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      相关资源
      最近更新 更多