Angularチュートリアルで使うWEBAPI作成
Angular公式のチュートリアルの「Tour of Heroes」をやっていくと、6章でサーバーサイドと通信を行う部分があります。
チュートリアル通りにやるなら In-memory Web APIモジュールを使用して、サーバーサイドをシミュレートしますが、ここでは.NETで自作していきます。
環境
- .NetFramework 4.7.2
- VisualStudio2019 community
- Angularチュートリアルの6章までやってあるAngularプロジェクト
Modelの用意
ヒーロー達を用意する必要があるので、クラスを作成
publicclassHero{publicHero(intid,stringname){this.id=id;this.name=name;}publicintid{get;set;}publicstringname{get;set;}}初期値の用意
DBは使わないので、staticで用意します。
初回だけコンストラクタでListに追加して、初期表示のヒーローリストを作成します。
publicclassValuesController:ApiController{publicstaticList<Hero>Heroes=newList<Hero>();publicstaticstring[]Names={"Sato","Suzuki","Takahashi","Tanaka","Ito","Watabe","Yamamoto","Nakamura","Kobayashi","Kato"};// コンストラクターstaticValuesController(){for(inti=1;i<=10;i++){Heroes.Add(newHero(i,Names[i-1]));}}//成功200privateHttpResponseMessageResponse200(){HttpResponseMessageresponse=Request.CreateResponse(HttpStatusCode.OK,"value");returnresponse;}//エラー400privateHttpResponseMessageResponse400(){HttpResponseMessageresponse=Request.CreateResponse(HttpStatusCode.BadRequest,"value");returnresponse;}-各種アクション-}GET
GETは一覧取得/単体取得/検索の3種類のアクションを用意
// GET 一覧取得publicIEnumerable<Hero>Get(){returnHeroes;}// GET 詳細publicHeroGet(intid){try{returnHeroes[id-1];}catch(Exceptionex){Console.WriteLine(ex.Message);returnnull;}}// GET 部分一致検索(大小区別なし)publicIEnumerable<Hero>Get(stringname){returnHeroes.Where(m=>m.name.ToUpper().Contains(name.ToUpper()));}POST
IDの最大値を取得して、ヒーローリストに追加しています。
// POST 追加publicHeroPost([FromBody]Herohero){intmaxId=Heroes.Max(m=>m.id)+1;Heroes.Add(newHero(maxId,hero.name));returnnewHero(maxId,hero.name);}PUT
IDで一致するヒーローの名前を変更する。
// PUT 更新publicHttpResponseMessagePut([FromBody]Herohero){try{Heroes.Where(m=>m.id==hero.id).FirstOrDefault().name=hero.name;returnResponse200();}catch(Exceptionex){Console.WriteLine(ex.Message);returnResponse400();}}DELETE
IDが一致するヒーローをリストから削除します。
// DELETE 削除publicHttpResponseMessageDelete(intid){try{Heroes.Remove(Heroes.Where(m=>m.id==id).FirstOrDefault());returnResponse200();}catch(Exceptionex){Console.WriteLine(ex.Message);returnResponse400();}}とりあえずCRUDはこれで動作します。
その他
ポートが違うとクロスオリジンで怒られるので、コントローラーに EnableCors属性をつけておく。
[EnableCors(origins:"http://localhost:4200",headers:"*",methods:"*")]
循環参照で怒られる?ので Global.asaxに下記を追加
参考:Web APIで応答をシリアル化できませんでした
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling=Newtonsoft.Json.ReferenceLoopHandling.Ignore;GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);こんな感じです。
API作成は.NetFrameworkも.NetCoreもあまり変わらない気がします。