C#
定石3:ルート制約({id:int}等)で型違いを弾く
出典: ASP.NET MVC 5 のルーティングを WinForms の Form 切替で理解する — 定石3:ルート制約({id:int}等)で型違いを弾く
// ✅定石3:ルート制約で型違いを弾く
public class OrderController : Controller
{
[Route("order/{id:int}")] // idはintのみ受け付ける
public ActionResult Detail(int id){ /* ... */ }
[Route("order/code/{code:alpha:length(8)}")] //英字8桁のcodeのみ
public ActionResult ByCode(string code){ /* ... */ }
[Route("order/{guid:guid}")] // GUID形式のみ
public ActionResult ByGuid(Guid guid){ /* ... */ }
[Route("order/{date:datetime}")] //日付形式のみ
public ActionResult ByDate(DateTime date){ /* ... */ }
}
▸ この snippet は実行結果未収録
▸ 実行結果は未収録です
Source収録記事
この snippet は記事の「定石3:ルート制約({id:int}等)で型違いを弾く」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。
同じ記事から
7 件// ✅定石1:デフォルトルート({controller}/{action}/{id}) using System.Web.Mvc; using System.Web.Routing;未収録
定石1:デフォルトルート(Convention-based)の仕組み
#eaf21dbee88d
// ✅定石2:属性ルート([Route] でActionに直接指定) [RoutePrefix("customer")] // Controller全体のプレフィックス public class CustomerController : Controller {未収録
定石2:属性ルート(Attribute-based)— URLを綺麗にしたい時
#afa2285308b5
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}");未収録
定石2:属性ルート(Attribute-based)— URLを綺麗にしたい時
#dddd922ca09a
// ✅定石4:カスタム階層ルート(API風) [RoutePrefix("api/v1")] public class OrdersApiController : Controller {未収録
定石4:カスタム階層ルート— REST風APIのような綺麗なURL
#8f6a81a42b29
// ✅ WinForms版: Formを切り替える public partial class CustomerListForm : Form { private void btnNewCustomer_Click(object sender, EventArgs e)未収録
定石5: Form切替↔ RedirectToActionの対比
#20c252589300
// ✅ ASP.NET MVC版: Actionにリダイレクト public class CustomerController : Controller { public ActionResult Index(){ /* 一覧表示 */ }未収録
定石5: Form切替↔ RedirectToActionの対比
#807d04442041