2008年6月3日火曜日

MVCContribでRESTful

CodeProject: RESTful routing in ASP.NET MVC. Free source code and programming help こんなに簡単に...。

SimplyRestfulRouteHandlerを使えばいいよ!ってことですね。 そもそもMVCContribってなんですか?ってなもんです。

なので、ちょっとソースをダウンロードして確認(現時点でのダウンロードが55っていうのが人気の無さを物語ってる気がしなくもなくもないけど気にしない!)。 かゆい所に手が届く系のライブラリって感じ?

RESTfulを単純にHTTP Methodだけで考えれば、リソースに対してGET/PUT/DELETE/POSTでアクションを決定するようにすればいいよね。ってことはリソース=Actionじゃなくて、リソース=Controller。 でも、WebでHTMLをViewにする場合、入力ページ(新規と編集)もGETだからリソースのGETとかぶる。あと、コレクションのGETも。 そうなると少し面倒な感じがしなくもないけど、RoutingでうまいことなんとかなるのがASP.NET MVCのいいところ。 URIの設計をしてて思ったのは、URIのリソースをそのままコントローラと一致させないで、以下に内包したコントローラとして頭を切り替えるかが結構キモなんですね。

会社と社員を内包関係で表現すると /Companies/{companyId}/Employees/{employeeId}

だけど、それぞれがコントローラになるんですよ~。 てことは、個別にしてもいいじゃない?

/Companies/{companyId} /Employees/{employeeId}

でも、これだと所属を表現できないからヤダってこともあるでしょう(会社と社員じゃないサンプルの方がよかったね...)。 デフォルトアクションがそれぞれIndexだとしたら、CompaniesController.Indexと EmployeesController.Indexがそれぞれのコレクションリソースで、個別のリソースを取得するためにもうひとつModelアクションを定義。で、RoutingでうまくModelアクションにルーティングしてあげればうまいこと出来るよね。

GET /Companies → 会社一覧取得 GET /Companies/New→ 会社新規フォーム POST /Companies → 会社新規登録 GET /Companies/123 → IDが123の会社取得 GET /Companies/123/Edit → IDが123の会社編集フォーム PUT /Companies/123 → IDが123の会社更新 DELETE /Companies/123 → IDが123の会社削除

こうしたいって時のコントローラでのアクション。 ※前回書いたRESTfulAttributeがある前提。

[RESTful(Post="Create")]
public ActionResult Index(int? id) {...}

[RESTful(Put="Update",Delete="Destroy")]
public ActionResult Model(int? id)
{
 if (id.HasValue)
  return Show(id);
 else
  return New();
}

public ActionResult Update(int id) {...}
public ActionResult Destroy(int id) {...}
public ActionResult Show(int id) {...}
public ActionResult New() {...}

これをうまくRoutingでさばきます。

routes.MapRoute( "Companies-Model", "Companies/{id}/{action}", new { controller="Companies", action="Model" }, new { id = @"[\d]+" } ); routes.MapRoute( "Companies", "Companies/{action}", new { controller="Companies", action="Index" }, new { action=@"[a-zA-Z]*" } );

こうやって、2つのRoutingでひとつのコントローラに対する、ルーティングを登録すればIDのありなしをちゃんと1つのコントローラで処理できるから、なんて素敵にRESTful!ってなりませんかね。 ※正規表現はよしなに。

ROAなURIを考えた場合{controller}/{action}/{id}だとアクションがリソースになるけど、{controller}/{id}/{action}でコントローラをリソースにしちゃいましょうっていう。

/Companies/123/Employees/456

とかのルーティング↓。

routes.MapRoute(
 "Employees-Model",
 "Companies/{companyId}/Employees/{id}/{action}",
 new { controller="Employees", action="Model" },
 new { companyId=@"[\d]+", id = @"[\d]+" }
); 

※コレクション部のルーティングも同じように。

イロイロ内包するならたくさん書くか、"/Employees"を"/{controller}"にしてあげる。 統一インターフェースでのアクセスは規約でアクションを決め打ちすることで最強になるでしょう。 全然MVCContribの話じゃないっすね...。

で、これを簡単にするのにMVCContrib。 Simply Restful Routing ここにあるように、アクション名を規約に通りにつければ、HTTP MethodとURIを見て、うまいことルーティングしてくれます。PUT/DELETEはブラウザから送れないので、そこはHidden で"_method"にメソッド名を入れてオーバーロードPOST。Railsっぽく。 どっちを使うかは気分次第で!

2008年5月29日木曜日

進化の過程をウキウキウォッチング

いや~、ずいぶん変わってしまいました。 Preview2からPreview3への移行をしてみようと作業してて思ったのが、簡単にできるようになったかもってところです。 もちのろんでASP.NET MVC Preview3ですよ! 分かりやすくRESTfulフィルター作ります。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication4.p3
{
 public class RESTfulAttribute : ActionFilterAttribute
 {
   public string Post { get; set; }
   public string Put { get; set; }
   public string Delete { get; set; }

   public RESTfulAttribute() : this("", "", "") { }
   public RESTfulAttribute(string post, string put, string delete)
   {
     Post = post;
     Put = put;
     Delete = delete;
   }

   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
     string httpMethod = filterContext.HttpContext.Request.HttpMethod.ToLower();
  
httpMethod = (filterContext.HttpContext.Request.Form["_method"] ??
filterContext.HttpContext.Request.HttpMethod).ToLower();

     var actions = new Dictionary() {
       {"post",Post!="" ? Post : filterContext.ActionMethod.Name + "Post" },
       {"put",Put!="" ? Put : filterContext.ActionMethod.Name + "Put"},
       {"delete",Delete!="" ? Delete : filterContext.ActionMethod.Name + "Delete"}
     };

     if (actions.ContainsKey(httpMethod) && actions[httpMethod] != "")
     {
       filterContext.Cancel = true;
     
       var controller = filterContext.Controller as Controller;
       var actionInvoker = new ControllerActionInvoker(controller.ControllerContext);
       actionInvoker.InvokeAction(actions[httpMethod], new Dictionary());
     
       return;
     }

     base.OnActionExecuting(filterContext);
   }
 }
} 

はぁ、もうこの時点で違うんだね。 InvokeActionがControllerじゃなくて、ControllerActionInvokerクラスに移動になりました。 素直に呼び出せるからこれの方がいいね。 2個目のパラメータの意味が不明。MVCのソース見てもExecuteで↑みたいにnewしてる。 RESTful属性をつけたアクションの実行時にPOST/PUT/DELETE毎にアクションを振り分ける処理です。 属性のパラメータで名前を指定しなかった場合は、自動で呼び出しアクション名+HTTP MethodをInvoke対象のアクション名にしてます。

ホントはGETのときにNew(新規フォーム)/Edit(編集フォーム)/Show(表示だけ)を振り分けるのもID見たりしてフィルターでやった方がよりカッコよしかも。あと、どの表現(XHTML、JSON、XMLとか)を返すかとかも拡張子みたいな形で分けるとなお素敵さアップ。 続いてHomeControllerにアクションを追加。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication4.p3.Controllers
{
 public class HomeController : Controller
 {
   public ActionResult Index()
   {
     ViewData["Title"] = "Home Page";
     ViewData["Message"] = "Welcome to ASP.NET MVC!";

     return View();
   }

   public ActionResult About()
   {
     ViewData["Title"] = "About Page";

     return View();
   }

   [RESTful]
   public ActionResult Resource(int? id)
   {
     return Content(string.Format("GET!({0}) - {1}", Request.Form["value"], id), "text/html");
   }

   public ActionResult ResourcePost()
   {
     return Content(string.Format("POST!({0})", Request.Form["value"]), "text/html");
   }
 
   public ActionResult ResourcePut(int id)
   {
     return Content(string.Format("PUT!({0}) - {1}", Request.Form["value"], id), "text/html");
   }
 
   public ActionResult ResourceDelete(int id)
   {
     return Content(string.Format("DELETE!({0}) - {1}", Request.Form["value"], id), "text/html");
   }

   public ActionResult Item()
   {
     ViewContext vc = new ViewContext(ControllerContext, "dummy", "", null, null);
     var page = new ViewPage();
     page.Html = new HtmlHelper(vc, page);
     page.Url = new UrlHelper(vc);

     string partial_html = page.Html.RenderUserControl("~/Views/UserControls/Item.ascx");
     return Content(partial_html, "text/html");
   }
 }
} 

Resourceって言う名前のアクションを定義して、RESTful属性をくっつけました。 前 (Preview2)まで、単純にテキストを出力するのがなかったから、RenderTextなんてのをControllerにくっつけてたんだけど、新たにContentって言うメソッドで出力できるようになりましたね!ちなみに今回は使ってないけどJsonもあるよ!

最後のItemアクションはユーザーコントロール(ascx)の実行結果を出力するため(パーシャルっす)のサンプル。これは前とほぼ変わってないけど、全体的に引数の数が増えてる感じ?

最後にページ部分。Home/Index.aspxを書き換えてます。

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication4.p3.Views.Home.Index" %>

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%= Html.Encode(ViewData["Message"]) %></h2>

<p>
<a href="<%= Url.Action("Resource") %>/1" class="restful">GET</a>
<a href="<%= Url.Action("Resource") %>" class="restful">POST</a>
<a href="<%= Url.Action("Resource") %>/1" class="restful">PUT</a>
<a href="<%= Url.Action("Resource") %>/1" class="restful">DELETE</a>
</p>

<p>
 <a href="javascript://" class="partial">どろんじょ</a>
 <div id="partial"></div>
</p>

<script type="text/javascript">
Event.observe(window, 'load', function(){
 var baseAction = '<%= Url.Action("Resource") %>';
 $$('a.restful').each(function(anchor){
   anchor.observe('click',function(e){
     var method = anchor.innerHTML;
     var index = anchor.href.indexOf(baseAction);
     var url = index >= 0 ? anchor.href.substring(index) : baseAction;

     new Ajax.Request(url,{
       method: method,
       parameters:'value=restful',
       onComplete:function(ajax){
         alert(ajax.responseText);
       }
     });
     Event.stop(e);
   });
 });

 $$('a.partial').first().observe('click',function(e){
   new Ajax.Request('<%= Url.Action("Item") %>',{
     onSuccess:function(ajax){
       partial.innerHTML = ajax.responseText;
     }
   });
 });

});
</script>
</asp:Content>

UserControls/Item.ascxの中身は何でもいいんだけど、とりあえず↓。

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Item.ascx.cs" Inherits="MvcApplication4.p3.Views.UserControls.Item" %>
<div>
 <ul>
   <li>マジで恋する5秒前</li>
   <li>ムゴ、ン色っぽい</li>
 </ul>
</div>

処理を簡単にするために、Site.Masterでprototype.jsを読み込むようにしてます。 実行すると、最初が↓。 img.aspx

PUTリンクをクリックすると↓。

img.aspx2

んで、どろんじょリンクをクリックすると↓。

img.aspx3

これで今日からRESTful!

2026年06月16日の記事一覧

(全 23 件) そうきたか。マイクロソフトが新しく提案するAI搭載の「社員証」 「WSL」のバージョン3が開発者にもたらす大きなメリット Stack Overflow、AIエージェント同士が掲示板で技術情報を共有する「Stack Overflow fo...