2012-07-19 35 views
1

正如你不能使用PUT和DELETE大多數託管我想創建避免使用這些路線的網站,但我不能得到這工作..創造附加通用路由和mvc4刪除

我想這樣

api/someController/Add/someInt 

與此RESTsharp代碼

private RestClient client; 

public RESTful() 
    { 
     client = new RestClient 
     { 
      CookieContainer = new CookieContainer(), 
      BaseUrl = "http://localhost:6564/api/", 
      //BaseUrl = "http://localhost:21688/api/", 
      //BaseUrl = "http://madsskipper.dk/api/" 
     }; 
    } 

    public void AddFriend(int userId) 
    { 
     client.Authenticator = GetAuth(); 

     RestRequest request = new RestRequest(Method.POST) 
     { 
      RequestFormat = DataFormat.Json, 
      Resource = "Friends/Add/{userId}" 
     }; 

     request.AddParameter("userId", userId); 

     client.PostAsync(request, (response, ds) => 
     { 
     }); 
    } 

路線要在我FriendsController打這個方法

// POST /api/friends/add/Id 
[HttpPost] //Is this necesary? 
public void Add(int id) 
{   
} 

所以我在航線配置

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

加入,但我做到這一點時,我只是打我的FriensController的構造函數,而不是添加方法

編輯:

還試圖使此路線配置

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

但是相同的結果噸,所述控制器被擊中,但不作用


解決方案: 發現了參數用RESTsharp錯誤地加入,所以不是

RestRequest request = new RestRequest(Method.POST) 
    { 
     RequestFormat = DataFormat.Json, 
     Resource = "Friends/Add/{userId}" 
    }; 

    request.AddParameter("userId", userId); 

它應該是

 RestRequest request = new RestRequest(Method.POST) 
     { 
      RequestFormat = DataFormat.Json, 
      Resource = "Friends/Add/{userId}" 
     }; 

     request.AddUrlSegment("userId", userId.ToString()); 

回答

2

你可能包括您的API路線定義動作的名稱:

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

再有這樣的動作:

[HttpPost] 
public void Add(int id) 
{ 

} 

現在你可能會引發一個POST請求的URL /api/friends/add/123

[HttpPost]的屬性確保該動作只能使用POST謂詞被調用。如果你刪除它,你仍然可以調用它打通,但是這東西,你不應該與可能修改服務器上的狀態的動作做。

+0

這是有道理的,但我想它像這樣http://pastebin.com/A9nNqq26,它是不是工作,它仍然只打FriendsController構造,我有一個調用get()方法在同一控制器上這另一種方法這工作得很好http://pastebin.com/XcuHzE0i – Mech0z 2012-07-20 13:58:24