@84zume
Pro ASP.NET MVC 3 Framework CHAPTER 11
URLs, Routing, and Areas
目次
1. Routing System
2. Area
3. Beautiful URL
2
Routing System
3
Routing Systemとは
=URLをコントローラーやアクションと結び付ける仕組み
• Webフォームとの違い
Webフォームは、ページの物理的な場所がURLになる
URL -> http://XXXX.com/Top.aspx
物理パス -> c:¥inetpub¥wwwroot¥XXXX¥Top.aspx
=機能:Incoming URLの処理とOutgoing URLの生成
• I:コントローラーとアクションへのマッピング
• O:HTMLのリンクの生成
4
Incoming URLの話
URLを通して、アプリケーションに入ってくるときの話。
5
URL Pattern
http://84zumeworks.com/Admin/Person/10
6
ホスト名
1st Segment 2nd Segment
3rd Segment
MVCの良いところ
これらを何にマッピングするかを 柔軟に実装・変更できることが良いとこ
どこにマッピングルールを書くのか
= Global.asax の Application_Start です。
7
public class MvcApplication : HttpApplication { protected void Application_Start() { //... RegisterRoutes(RouteTable.Routes); } public static void RegisterRoutes(RouteCollection routes) { routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } }
RouteTableのRouteコレクションにマッピング情報を追加する
どうマッピングされるか
Incoming URL http://84zumeworks.com/Admin/Person/10
8
マッピングルール
"{controller}/{action}/{id}"
controller = “Admin” action = “Person” id = “10”
マッピングルールのバリエーション
9
routes.MapRoute( “84zumeWorksMap", "{controller}/{action}/{id}/{*catchall}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new { controller = "^H.*", httpMethod = new HttpMethodConstraint("GET"), customConstraint = new UserAgentConstraint("IE") }, new[] {"UrlsAndRoutes.Controllers"} );
名前
マッピング方法
デフォルト値
制約
探す名前空間
Outgoing URLの話
HTMLに出力されるURLの話
10
どう出力されるか
<a ref=“Home/About”>Here</a>
11
@Html.ActionLink(“Here”, “About”)
<a ref=“Catalog/List?page=789”>Here</a>
@Html.ActionLink( “Here”, “List”, “Catalog”, new {page=789})
※マッピングルールに従う。
Routing Systemの拡張ポイント
12
Routing Systemの拡張ポイント
• RouteBaseをオーバーライドする。 {controller}や{action}以外のマッチング規則を追加できる。
サブドメインに基づくルーティングも書ける。
http://warehouse.84zumeworks.com/
• IRouteHandlerを実装する。
そもそものルーティングの仕組みを変更できる。
→
ちなみに…MVCRouteHandler(MvcHandler)は
controllerのインスタンス化とかを内部的にしてる。
13
Area
14
Areaとは
=大きなアプリを分割できる仕組み
• 例
• 右のような感じ
• 階層がなんかいけてない
• 分割例
• 本体
• 管理者画面
• http://84zumeworks.com/Admin
• Adminエリアのデフォルトコントローラー
• Adminコントローラー
15
Beautiful URL
16
URLは大事。
17
http://omniti.com/helps/national-geographic
おわりに
18
まとめ
1. URLには2種類の意味があることを覚えるべし
2. Areaをつかってサイトを上手に分割すべし
3. きれいなURLを意識するべし
19
参考文献
• CodePlex
「ASP.NET MVC 3 RTM」
http://aspnet.codeplex.com/releases
20