前幾天,按照AngularJS2的英雄指南教程走了一遍,教程網址是http://origin.angular.live/docs/ts/latest/tutorial/。
在步驟完成后,又更進一步,在英雄增刪改的時候,直接調用.net core的WebApi來實現后台數據的操作,替換教程中的模擬WebApi方式。在替換.net core WebApi時,還是遇到了一些坑的,這里記錄一下。
先來看一下WebApi和AngularJS的源代碼:
WebApi

1 [Route("api/[controller]")] 2 public class ValuesController : Controller 3 { 4 private List<Hero> heroes; 5 6 public ValuesController() 7 { 8 heroes = GetHeroes() 9 10 } 11 12 [HttpGet] 13 public IEnumerable<Hero> Get() 14 { 15 return heroes; 16 } 17 18 [HttpGet("{id}")] 19 public Hero Get(int id) 20 { 21 return heroes.Single(h => h.Id == id); 22 } 23 24 [HttpGet] 25 [Route("GetList")] 26 public IEnumerable<Hero> GetList(string key) 27 { 28 return heroes.Where(h => h.Name.Contains(key)); 29 } 30 31 [HttpPost] 32 public void Post([FromBody]Hero info) 33 { 34 Hero hero = new Hero(); 35 36 hero.Id = heroes.Max(h => h.Id) + 1; 37 hero.Name = info.Name; 38 39 AddHeroes(hero); 40 } 41 42 [HttpPut("{id}")] 43 public void Put(int id, [FromBody]Hero hero) 44 { 45 Hero x = heroes.Single(h => h.Id == id); 46 47 x.Name = hero.Name; 48 49 UpdateHeroes(x); 50 } 51 52 [HttpDelete("{id}")] 53 public void Delete(int id) 54 { 55 Hero hero = heroes.Single(h => h.Id == id); 56 RemoveHeroes (hero); 57 } 58 }
AngularJS

1 getHeroes(): Promise<Hero[]> { 2 return this.http.get(this.heroUrl).toPromise().then(response => response.json() as Hero[]).catch(this.handleError); 3 } 4 5 getHero(id: number): Promise<Hero> { 6 return this.getHeroes().then(heroes => heroes.find(hero => hero.id === id)); 7 } 8 9 getHeroesSlowly(): Promise<Hero[]> { 10 return new Promise<Hero[]>(resolve => 11 setTimeout(resolve, 2000)) // delay 2 seconds 12 .then(() => this.getHeroes()); 13 } 14 15 updateHero(hero: Hero): Promise<Hero> { 16 const url = `${this.heroUrl}/${hero.id}`; 17 return this.http 18 .put(url, JSON.stringify(hero), { headers: this.headers }) 19 .toPromise() 20 .then(() => hero) 21 .catch(this.handleError); 22 } 23 24 addHero(heroName: string): Promise<Hero> { 25 return this.http 26 .post(this.heroUrl, JSON.stringify({ name: name }), { headers: this.headers }) 27 .toPromise() 28 .then(response => response.json()) 29 .catch(this.handleError); 30 } 31 32 deleteHero(heroId: number): Promise<void> { 33 const url = `${this.heroUrl}/${heroId}`; 34 return this.http 35 .delete(url, { headers: this.headers }) 36 .toPromise() 37 .then(() => null) 38 .catch(this.handleError); 39 } 40 41 search(term: string): Observable<Hero[]> { 42 return this.http.get(`${this.heroUrl}/GetList?key=${term}`).map((r: Response) => r.json() as Hero[]); 43 } 44 45 private handleError(error: any): Promise<any> { 46 console.error('An error occurred', error); // for demo purposes only 47 return Promise.reject(error.message | error); 48 }
一、跨域訪問(Cors)問題
在建好WebApi站點,啟動運行,一切正常。我們僅顯示前兩個Action,結果如下:
然而,在AngularJS客戶端,出現了問題,界面沒有任何英雄出現。
再查Chrome的控制台,發現了問題所在,WebApi的Access-Control-Allow-Origin沒有開,也就是跨域訪問不通過。
跨域訪問,就是JS訪問其他網址的信息。例如這里的AngularJS的
1 getHeroes(): Promise<Hero[]> { 2 return this.http.get(this.heroUrl).toPromise().then(response => response.json() as Hero[]).catch(this.handleError); 3 }
方法中,調用heroUrl(WebApi網址)。AngularJS的網址是http://localhost:3000/,而WebApi的網址是http://localhost:5000/api/values。只要協議、域名、端口有任何一個不同,都被當作是不同的域。默認情況下是不支持直接跨域訪問的。為了在WebiApi中增加跨域訪問,我們要在WebApi的Startup.cs中打開Access-Control-Allow-Origin:
1 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 2 { 3 app.UseCors(builder => 4 { 5 builder.AllowAnyOrigin(); 6 }); 7 8 app.UseMvc(); 9 }
現在程序訪問正常。
我們查看AngularJS網站的network情況,在values的headers—Response Headers中有Access-Control-Allow-Origin: *的字樣,這樣就解決了前面出現的"No Access-Control-Allow-Origin header is present…"錯誤。
再繼續測試,又出現問題了,這次是在更新時
錯誤信息如下:
我們都已經打開Access-Control-Allow-Origin,怎么還報錯:"No Access-Control-Allow-Origin header is present…"?我們回過來看AngularJS,調用的是Update:
1 updateHero(hero: Hero): Promise<Hero> { 2 const url = `${this.heroUrl}/${hero.id}`; 3 return this.http 4 .put(url, JSON.stringify(hero), { headers: this.headers }) 5 .toPromise() 6 .then(() => hero) 7 .catch(this.handleError); 8 }
對應WebApi,這次調用的是Put方法
1 [HttpPut("{id}")] 2 public void Put(int id, [FromBody]Hero hero) 3 { 4 Hero x = heroes.Single(h => h.Id == id); 5 6 x.Name = hero.Name; 7 8 UpdateHeroes(hero.Name); 9 }
是不是由於Method不對啊,以前都是Post、Get,這次是Put。趁早,一不做,二不休,在WebApi的Startup.cs中,寫成如下:
1 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 2 { 3 app.UseCors(builder => 4 { 5 builder.AllowAnyOrigin(); 6 builder.AllowAnyHeader(); 7 builder.AllowAnyMethod(); 8 }); 9 10 app.UseMvc(); 11 }
允許所有Origin、Header和Method。這次徹底搞定,運行正常。
二、Update方法,必須使用類
其實上面Update時,還是遇到了部分問題的。就是按照最開始的程序,我們在WebApi的Put方法中,傳入的是英雄名稱name,而不是Hero對象。
1 [HttpPut("{id}")] 2 public void Put(int id, [FromBody]string name) 3 { 4 Hero x = heroes.Single(h => h.Id == id); 5 6 x.Name = name; 7 8 UpdateHero(x); 9 }
同時AngularJS中如下:
1 updateHero(hero: Hero): Promise<Hero> { 2 const url = `${this.heroUrl}/${hero.id}`; 3 return this.http 4 .put(url, JSON.stringify({name: name}), { headers: this.headers }) 5 .toPromise() 6 .then(() => hero) 7 .catch(this.handleError); 8 }
在程序運行時,我們修改第13號英雄:
查看network,提交也是name: "Bombasto1111"。
然而,在WebApi中,調試情況下:
Id沒有問題,但是name是null。[FromBody]要求前台傳入的是Json串,然后提交到Action中。這時,Angular傳入的是{name: "Bombasto1111"},通過FromBody轉換后,是一個object,而不是一個string,因此name的值是null。
如果想用string name方式,AngularJS就要寫成:
1 updateHero(hero: Hero): Promise<Hero> { 2 const url = `${this.heroUrl}/${hero.id}`; 3 return this.http 4 .put(url, JSON.stringify(hero.name), { headers: this.headers }) 5 .toPromise() 6 .then(() => hero) 7 .catch(this.handleError); 8 }
再看network
WebApi調試狀態如下圖,name有值,一切搞定。
也可以使用Hero作為參數的方式,如同我們文檔最開始提供的代碼一樣。
1 updateHero(hero: Hero): Promise<Hero> { 2 const url = `${this.heroUrl}/${hero.id}`; 3 return this.http 4 .put(url, JSON.stringify(hero), { headers: this.headers }) 5 .toPromise() 6 .then(() => hero) 7 .catch(this.handleError); 8 }
[HttpPut("{id}")] public void Put(int id, [FromBody]Hero hero) { Hero x = heroes.Single(h => h.Id == id); x.Name = hero.Name; UpdateHeroes(x); }
三、路由改變
我們在做Hero Search的時候,又要在后台WebApi中編寫按照關鍵字查詢的方法
1 [HttpGet] 2 public IEnumerable<Hero> GetList(string key) 3 { 4 return heroes.Where(h => h.Name.Contains(key)); 5 }
如果僅僅這樣寫,整個WebApi都不好用了。在調用Get時,出現了喜聞樂見的500錯誤。
而調用Get(int id)方法,就是localhost:5000/api/values/11時,一切正常。這是為什么呢?
因為按照微軟的方式,如果有多個相同Method(例如HttpGet)的方法,WebApi路由就沒法區分了。這里,Get()和GetList(string key)都是[HttpGet],路由都是localhost:5000/api/values。而Get(int id)方法由於寫的是[HttpGet("{id}")],網址是localhost:5000/api/values/11,與Get()路由不同。因此,為了解決Get()和GetList(string key),我們在getlist方法上增加指定路由的方式。例如這里就是
1 [HttpGet] 2 [Route("GetList")] 3 public IEnumerable<Hero> GetList(string key) 4 { 5 return heroes.Where(h => h.Name.Contains(key)); 6 }
在AngularJS中,就可以使用localhost:5000/api/values/GetList?key=XXXX的方式調用,程序如下:
1 search(term: string): Observable<Hero[]> { 2 return this.http.get(`${this.heroUrl}/GetList?key=${term}`).map((r: Response) => r.json() as Hero[]); 3 }
當然了,如果想更進一步,需要再修改整個路由方式,增加Action。這就需要在Controller上增加[Route("api/[controller]/[action]/")]的寫法,並且將Action的[Route]刪除。
[Route("api/[controller]/[action]/")]
public class ValuesController : Controller
這次是真的解決了。