C# ASP.NET Web APIにおけるコントローラーアクションの4つの戻り値の型とは?
ASP.NET Web APIのアクションメソッドには、主に以下の4種類の戻り値の型を指定することができます。
void(戻り値なし)
プリミティブ型/複合型
HttpResponseMessage
IHttpActionResult
1. void(戻り値なし)
すべてのアクションメソッドが必ずしも何かを返す必要はありません。戻り値の型としてvoidを指定することも可能です。
コード例
using DemoWebApplication.Models;
using System.Web.Http;
namespace DemoWebApplication.Controllers
{
public class DemoController : ApiController
{
public void Get([FromBody] Student student)
{
// 何らかの処理
}
}
}

戻り値がvoidのアクションメソッドは、204 No Contentレスポンスを返します。これは「処理自体は成功したが、返すべきボディがない」ことを示すステータスコードです。
2. プリミティブ型/複合型
アクションメソッドは、intやstringといったプリミティブ型、あるいはList<string>などの複合型を直接返すこともできます。返されたデータは、JSONやXML形式に自動的にシリアライズされてクライアントへ送信されます。
コード例
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers
{
public class DemoController : ApiController
{
public List<string> Get([FromBody] Student student)
{
return new List<string>{
$"The Id of the Student is {student.Id}",
$"The Name of the Student is {student.Name}"
};
}
}
}

3. HttpResponseMessage
HttpResponseMessageは、アクションメソッドの戻り値(アクション結果)を細かくカスタマイズしたい場合に使用します。ステータスコード、コンテンツタイプ、そしてクライアントへ返すデータを明示的に指定することで、柔軟なレスポンス制御が可能になります。
コード例
using DemoWebApplication.Models;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace DemoWebApplication.Controllers
{
public class DemoController : ApiController
{
public HttpResponseMessage Get([FromBody] Student student)
{
if(student.Id > 0){
return Request.CreateResponse(HttpStatusCode.OK,
$"The Student Id is {student.Id} and Name is {student.Name}");
} else {
return Request.CreateResponse(HttpStatusCode.BadRequest,
"Invalid Student Id");
}
}
}
}

上記の例では、レスポンスがカスタマイズされていることがわかります。アクションメソッドに渡されたIdが0であるためelseブロックが実行され、指定されたエラーメッセージとともに400 Bad Requestが返されています。
4. IHttpActionResult
IHttpActionResultインターフェースはWeb API 2で導入されました。本質的には、HttpResponseMessageを生成するためのファクトリ(生成装置)を定義するものであり、System.Web.Http名前空間に含まれています。HttpResponseMessageを直接扱う場合と比較した、IHttpActionResultを使用する主なメリットは以下の通りです。
コントローラーの単体テスト(ユニットテスト)がシンプルになる。
HTTPレスポンスを生成する共通ロジックを、独立したクラスに切り出せる。
レスポンス構築の低レベルな詳細を隠蔽できるため、コントローラーアクションの意図がより明確になる。
コード例
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers
{
public class DemoController : ApiController
{
public IHttpActionResult Get([FromBody] Student student)
{
var result = new List<string>{
$"The Id of the Student is {student.Id}",
$"The Name of the Student is {student.Name}"
};
return Ok(result);
}
}
}

このようにOk()ヘルパーメソッドを使えば、200 OKレスポンスを簡潔に返すことができます。ほかにもBadRequest()やNotFound()など、目的に応じた便利なヘルパーメソッドが多数用意されており、可読性とテスト容易性の高いコードを実現できます。
-
C# ASP.NET Web APIのアクションメソッドからカスタム結果タイプを返す方法
ASP.NET Web APIでは、IHttpActionResultインターフェースを実装することで、独自のカスタムクラスを結果タイプとして作成できます。IHttpActionResultインターフェースには、HttpResponseMessageインスタンスを非同期に生成する単一のメソッド ExecuteAsync が定義されています。public interface IHttpActionResult { Task<HttpResponseMessage> ExecuteAsync( CancellationToken cancellationToke
-
OSのカーネルとは?役割・仕組みと5つの種類をわかりやすく解説
Windows、macOS、Linux、Androidなど、あらゆるオペレーティングシステム(OS)には「カーネル(Kernel)」と呼ばれる中核プログラムが存在します。カーネルはシステム全体の「ボス」のような存在であり、まさにOSの心臓部です。コンピューター上で起こるあらゆる処理はカーネルを経由し、他のすべてを制御するコンピュータープログラムでもあります。本記事では、OSにおけるカーネルとは何か、そしてカーネルにはどのような種類があるのかを詳しく解説します。 OSにおけるカーネルとは カーネルはOSの中核プログラムであるだけでなく、ブートローダーの実行後に最初に読み込まれるプログラムでもあり