2015-07-28 31 views
0

我想讓我的API在我的C#控制檯應用程序中工作。我已經定義了幾個控制器:C#ApiController HttpPost

using System.Web.Http; 
using Velox.Maple.Data; 

namespace Velox.API.Controllers 
{ 
    internal sealed class CharacterController : ApiController 
    { 
     [HttpGet] 
     public int Count() 
     { 
      return CharacterDataProvider.Instance.Count; 
     } 

     [HttpPost] 
     public void SetMap(int mapId) 
     { 

     } 
    } 
} 

請注意,它需要mapId作爲參數。

我使用RestSharp來測試我的API。以下是執行請求的代碼:

private void button1_Click(object sender, EventArgs e) 
     { 

      var client = new RestClient("http://localhost:8999"); 
      var request = new RestRequest(Method.POST); 

      request.Resource = "character/SetMap"; 
      request.AddParameter("mapId", 100000000); 

      var response = client.Execute(request); 

      var data = response.Content; 

      MessageBox.Show("Data: " + data); 
     } 

     private void button2_Click(object sender, EventArgs e) 
     { 
      var client = new RestClient("http://localhost:8999"); 
      var request = new RestRequest(Method.GET); 

      request.Resource = "character/OnlineCount"; 

      var response = client.Execute(request); 

      var data = response.Content; 

      MessageBox.Show("Online: " + data); 

     } 

第二個按鈕正常工作。它確實返回值,它工作得很好。但是,第一個按鈕不起作用。它說它出於某種原因找不到具體的方法。

我在做什麼錯?

回答

0

我認爲您需要使用我喜歡稱的請求模型

[HttpPost] 
public void SetMap(MapRequest req) 
{ 
    //now you have access to req.MapId 
} 

public class MapRequest 
{ 
    public int MapId {get;set;} 
} 

這允許請求主體被正確地反序列化和綁定。

0

WebApi控制器操作對它們接收的參數非常敏感。我敢肯定它沒有在這個解析:

("mapId", 100000000); 

爲int的azazaz

確保您正確使用AddParameter方法。

0

你需要用斜線分隔你的控制器/動作。

request.Resource = "character/Count"; 

也,你在指定的無效動作名稱有:

request.Resource = "character/OnlineCount"; 

沒有方法 'OnlineCount'

0

首先,CharacterController不能內部,簡單的類型參數(例如:int,long ...)從url查詢中獲取值,RestSharp在body中發佈mapId,這就是爲什麼mvc無法找到操作。你可以像這樣標記mapId:([FromBody]int mapId),或者傳遞url中的mapID: character/SetMap?MapId = 1000

+0

我試圖使用'FromBody'屬性,但是mapId的值是0。 '添加參數,如:'request.AddParameter(「mapId」,1000);' –

+0

@GilbertWilliams請參閱:http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/如果你不想改變你的代碼來接受一個對象參數,你可以像這樣提交參數:'request.AddParameter(「」,1000)' – aspark