2016-12-07 60 views
0

我正在嘗試使用web api在測試學習器項目中使用angular 2,但我用http.put命中了一個問題並且想知道如果任何人都可以闡明它。http.put使用Chrome瀏覽器而不是IE瀏覽器在Angular 2/Web API中拋出錯誤

我可以發佈一個對象到web api,我可以從它獲取數據。

我在使用Chrome時遇到了PUT問題。我之所以說使用Chrome的原因是,它不適用於Chrome,但在IE中工作 - 通常不會這麼說;)

我使用的angular 2方法是這樣的。如果我用POST替換PUT,我可以在我的web api控制器中找到斷點,但是使用PUT no可以。

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'); 
     }); 
} 

控制檯瀏覽器的錯誤信息使用看跌期權,當我:

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 

的網絡API方法都直開箱。我還沒有做任何事情。如果我在POST上放置了一個斷點,它會被擊中,而不是PUT。

 // POST api/user 
    public void Post(User user) 
    { 
    } 

    // PUT api/user/5 
    public void Put(User user) 
    { 
    } 

的網頁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。它如何在IE中起作用?

任何想法?

回答

0

好吧,我得到了這個工作。角2側很好。 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> 

就是這樣。

相關問題