2011-12-01 81 views
3

我正在使用ASP.NET MVC 3.我對它很陌生。我想我已經開始掌握它了。但有一些我正在努力做的,我認爲是有道理的,但也許我錯了。使用ASP.NET MVC3推薦的API設計

我正在嘗試在我的數據庫中的Order對象周圍創建一個API。爲了獲得系統中所有的命令,我要揭露,看起來像下面的API:

/命令/

在我想獲得一個特定的順序的情況下,我只想附加一個ID。換句話說,該URL應該是這樣的:

/命令/ 12345

在努力做到這一點,我創建了以下控制器:

public class OrdersController : Controller 
{ 
    // GET: /Orders/ 
    [AcceptVerbs(HttpVerbs.Get)] 
    public ActionResult Index() 
    { 
     string result = "list of orders"; 
     return Json(result, JsonRequestBehavior.AllowGet); 
    } 

    // 
    // GET: /Orders/{orderID} 
    public ActionResult Index(int id) 
    { 
     string result = "order:" + id; 
     return Json(result, JsonRequestBehavior.AllowGet); 
    } 
} 

在我AreaRegistration類,我有以下內容:

public override void RegisterArea(AreaRegistrationContext context) 
    { 
    context.MapRoute(
     "OrderList", 
     "{controller}/{action}", 
     new { action = "Index", controller="Orders" } 
    ); 

    context.MapRoute(
     "Order", 
     "{controller}/{action}/{id}", 
     new { action = "Index", controller = "Orders" } 
    ); 
    } 

當我試圖訪問「/命令/」,通過瀏覽器地址欄,我得到的JSON像我期望的那樣。但是,如果我試圖訪問「/ orders/12345」,我會收到404。我錯過了什麼?

謝謝

+3

你的路由表是什麼樣的? –

+0

我沒有做任何事情。由於該控制器位於Area內,因此我不確定在哪裏設置路由。 –

回答

4

您需要在global.asax也定義適當的路由或使用它看起來像{controller}/{action}/{id}中,控制器默認爲「家」的默認路由,動作被默認爲「索引」和id是可選的。

所以/orders作品,因爲你已經定義控制器(單),默認操作(指數)和缺少ID(這並不重要,因爲它是可選的)

但是當你嘗試/orders/12345然後選擇已經定義控制器(訂單),行動(12345)和缺少ID

所以爲了讓只有缺省路由這項工作的要求應該是/orders/index/12345

編輯:登記面積的路線,你應該使用AreaRegistration類

+0

我在這裏同意100%+1,只添加如果你想要一個單獨的路由,只需將它添加到默認路由之上,並指定/ orders/{id}。 –

+0

這就是我暗示的。 +1 :) –

+0

我添加了以下內容到我的AreaRegistration中,並且我仍然得到一個404「context.MapRoute( 」Order「, 」{controller}/{action}/{id}「, new {action =」Index 「,controller =」Orders「} ); –