2014-03-05 64 views
1

我已經添加了這個方法我的網絡API控制器:ASP.net的Web API 2自定義方法

[HttpPost] 
    public bool CreateTrening(int routineId) 
    { 
     try 
     { 
      var userId = User.Identity.GetUserId(); 
      TreningService.CheckIfLastTrenigWasCompleted(userId); 
      TreningService.CreateTreningForUser(userId, routineId); 
      return true; 
     } 
     catch (Exception ex) 
     { 
      return false; 
     } 
    } 

而且我已經加入到我的WebApiConfig文件另一條路線,所以它現在看起來是這樣的:

 config.MapHttpAttributeRoutes(); 

     config.Routes.MapHttpRoute(
      name: "CustomApi", 
      routeTemplate: "{controller}/{action}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 

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

但是當我嘗試打電話給我的方法:

/EditWorkout/CreateTrening/1

我得到這個呃ror:

{「Message」:「沒有找到與請求URI相匹配的HTTP資源」/EditWorkout/CreateTrening/1'.","MessageDetail":"沒有在控制器的EditWorkout上找到匹配的操作請求。「}

如何調用我在WebApi控制器中的方法?

回答

1

使用該URL調用post方法將不起作用,因爲該帖子期望在Http Message正文中傳輸的值。不在URL中,所以你的控制器沒有找到方法。

也許最好的解決方案是在您發送控制器的http消息中編碼您的發佈值,並使用/ EditWorkout/CreateTrening調用URL,這將作爲發佈。

這裏是另一個SO跟帖其中如何做到這一點的問題得到回答, Specific post question answered

相關問題