0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[.NETでのWebアプリ 第5回] ASP.NETの闇・Controllerクラスの注意点

Last updated at Posted at 2025-09-04
Page 1 of 8

C#でREST APIを実装するのに、Contrllerクラスは便利!

(名前空間はMicrosoft.AspNetCore.Mvc


HTTP応答コードに応じた多彩なレスポンスを簡単に返すことができる

[HttpGet]
public async Task<ActionResult<Account>> GetCurrentAccount()
{
    var user = await _userManager.GetCurrentUser();
    return user is null
        ? NotFound()
        : Ok(user)
        ;
}

Controllerのよいところ

  • リクエストやレスポンスのデータは、自動でJSONにエンコード/デコードされる
  • 属性を使うことでHTTPのどの部分を使ってデータを受信するか、簡単に指定できる
[HttpGet]
public async Task<ActionResult<List<User>>> GetAccounts(
    [FromQuery] int page, [FromQuery] int countPerPage
)
{
    var users = await _userManager.GetUsers(page, countPerPage);
    return Ok(users);
}

便利な反面、Controllerには致命的な設計ミスがある

以下のコードがエラーにならない!警告すら出ない!

[HttpGet]
public ActionResult<Account> GetCurrentAccount()
{
    return Ok(0);
}

  • C#の良さの1つは豊富な型
  • なのにそれを失う・・・

対策は?

  • 現時点ではIActionResult/ActionResultを使わない、という選択肢しかない・・・
  • 基本、200を返すようにし、エラー内容はレスポンスボディで表現する
    RESTらしさの放棄・・・

最後に

  • RESTらしさを捨てるか型安全性を捨てるかの2択を迫られる
  • 個人的には型安全性を優先させたい
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?