2012-07-30 57 views
1

在我TestController我有以下幾點:MVC網頁API路由的默認動作不靈

[HttpGet] 
    public IEnumerable<String> Active() 
    { 
     var result = new List<string> { "active1", "active2" }; 

     return result; 
    } 

    [HttpGet] 
    public String Active(int id) 
    { 
     var result = new List<string> { "active1", "active2" }; 

     return result[id]; 
    } 

RouteConfig的映射是:

routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 

     routes.MapHttpRoute(
      name: "ActionApi", 
      routeTemplate: "api/{controller}/{action}/{id}", 
      defaults: new { action = "", id = RouteParameter.Optional }); 

在瀏覽器下面的請求的工作原理:

api/test/active/1 

但是,這返回內部服務器錯誤

api/test/active 

那你必須做返回動作可能或maynot有一個參數,以類似的方式爲默認獲取?

更新1 作爲的Cuong樂建議,改變路線的順序的幫助下,該航線目前有:

routes.MapHttpRoute(
      name: "ActionApi", 
      routeTemplate: "api/{controller}/{action}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 

     routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 

     routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 

我不得不從ActionApi路線刪除action = ""否則標準獲取的其他控制器停止工作(即api /值)

api/test/active現在正在解決,但我現在得到一個500內部服務器錯誤的/ api /測試是可以解決,所以API /測試將返回「所有「和/測試/主動只返回」一些「?

+0

你會得到什麼樣的內部服務器錯誤的?多個行動被發現? – 2012-07-30 16:40:00

+0

對不起,我不確定如何獲取更詳細的消息,我正在運行只是在Visual Studio中使用調試,是否有一個web.config設置或什麼可以得到一個更詳細的錯誤? – HadleyHope 2012-07-30 17:17:00

+0

我還沒有嘗試調試BU我認爲你可以看到調試的詳細錯誤。您也可以在web.config上設置並使用過濾器查看拋出的錯誤。至於你的問題,我到目前爲止還沒有明確的答案:(。 – 2012-07-31 11:14:27

回答

0

由於您有兩個名爲action的方法,可能會感到困惑。嘗試刪除或重命名其中一個,看看是否有效。

+0

)如果我在控制器中註釋掉Active(int id),我得到一個400的錯誤請求api/test/active。我會想到兩種方法一使用一個沒有參數的函數就可以,因爲默認的例子Get()和Get(int id)工作。 – HadleyHope 2012-07-30 16:44:01

0

一種方式來做到這一點是提供參數的默認值,

[HttpGet] 
public String Active(int id = 0) 
{ 
    var result = new List<string> { "active1", "active2" }; 

    if (id == 0) { 
     return result; 
    } else { 
     return result[id]; 
    } 
} 
+0

Darrel,返回類型將不同,如果id == 0 Enumerable將被返回。是將「操作」添加到Url時的路由。 – HadleyHope 2012-07-30 16:47:01