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?

【ASP.NET Core MVC】ルート制約まとめ

0
Posted at

【ASP.NET Core MVC】ルート制約まとめ(よく使うルーティング設計)

ASP.NET Core MVC のルーティングでは、URL を Controller / Action にマッピングします。
その際に重要になるのが Route Constraints(ルート制約) です。

ルート制約を使うことで、

  • URLパラメータの型を制限
  • 想定外のURLを排除
  • ルート競合を防止
  • REST API設計を明確化

することができます。

この記事では

  • 基本的なルート制約
  • よく使う制約
  • よく使うルーティングパターン

をまとめます。


ASP.NET Coreの基本的なルート制約

ルート制約とは

URLパラメータの型や条件を制限する仕組みです。

[HttpGet("users/{id:int}")]
public IActionResult GetUser(int id)
{
    return Ok(id);
}

よく使う制約一覧です。

制約 説明
int 整数 {id:int}
long long型 {id:long}
guid GUID形式 {id:guid}
bool true / false {flag:bool}
datetime 日付 {date:datetime}
alpha アルファベット {name:alpha}
length(x) 文字数制限 {code:length(6)}
min(x) 最小値 {age:min(18)}
max(x) 最大値 {age:max(60)}
regex 正規表現 {code:regex(...)}

int(最も使用頻度が高い)

ID指定のAPI

[HttpGet("products/{id:int}")]
public IActionResult Details(int id)
{
    return Ok(id);
}

用途

  • 商品詳細
  • ユーザー詳細
  • 編集画面
  • 削除対象

guid

識別子やトークン系

[HttpGet("orders/{id:guid}")]
public IActionResult GetOrder(Guid id)
{
    return Ok(id);
}

用途

  • 注文ID
  • ユーザーID
  • 招待URL
  • APIトークン

alpha

文字列のみのルート

[HttpGet("users/{name:alpha}")]
public IActionResult GetByName(string name)
{
    return Ok(name);
}

用途

  • ユーザー名
  • カテゴリ名
  • スラッグ

regex

書式制限

[HttpGet("products/{code:regex(^[A-Z]{3}[0-9]{3}$)}")]
public IActionResult GetProduct(string code)
{
    return Ok(code);
}

ABC123 → OK
AB123 → NG

複数制約

複数条件も可能です。

[HttpGet("users/{age:int:min(18):max(60)}")]
public IActionResult GetByAge(int age)
{
    return Ok(age);
}

条件

  • 整数
  • 18以上
  • 60以下

オプションパラメータ

[HttpGet("blog/page/{page:int?}")]
public IActionResult Index(int page = 1)
{
    return Ok(page);
}

URL

/blog/page/2
/blog/page

結果

page = 1

よく使うルーティングパターン

REST API設計

[HttpGet("products")]
public IActionResult GetAll()

[HttpGet("products/{id:int}")]
public IActionResult GetById(int id)

[HttpPost("products")]
public IActionResult Create()

[HttpPut("products/{id:int}")]
public IActionResult Update(int id)

[HttpDelete("products/{id:int}")]
public IActionResult Delete(int id)

REST設計のポイント

  • URLは 名詞
  • 操作は HTTPメソッド

ルート分岐

[HttpGet("users/{id:int}")]
public IActionResult GetById(int id)

[HttpGet("users/{name:alpha}")]
public IActionResult GetByName(string name)

URL

/users/10
/users/admin

Routing Engine が制約を使って判定します。


Reactとのルーティング

ReactからAPIを呼ぶ場合

fetch("/api/products/10")

ASP.NET Core

[HttpGet("products/{id:int}")]
public IActionResult GetProduct(int id)

流れ

React
 ↓
HTTP Request
 ↓
ASP.NET Routing
 ↓
Route Constraint
 ↓
Controller Action

LinkGeneratorとURL生成

URLをハードコードしないために LinkGenerator を使います。

[HttpGet("manage/settings", Name = "UserSettings")]
public IActionResult Settings()
{
    return View();
}

URL生成

var url = _linkGenerator.GetPathByName("UserSettings");

用途

  • メールURL生成
  • リダイレクト
  • APIレスポンスリンク

まとめ

ASP.NET Core MVC のルート制約は

  • URL型チェック
  • ルート競合防止
  • REST API設計
  • セキュリティ向上

に役立つ重要な仕組みです。

特に実務でよく使うのは

{id:int}
{id:guid}
{name:alpha}
regex

です。

ルーティングは単なるURLマッチではなく

API設計の基盤になります。

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?