我想讓我的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);
}
第二個按鈕正常工作。它確實返回值,它工作得很好。但是,第一個按鈕不起作用。它說它出於某種原因找不到具體的方法。
我在做什麼錯?
我試圖使用'FromBody'屬性,但是mapId的值是0。 '添加參數,如:'request.AddParameter(「mapId」,1000);' –
@GilbertWilliams請參閱:http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/如果你不想改變你的代碼來接受一個對象參數,你可以像這樣提交參數:'request.AddParameter(「」,1000)' – aspark