簡體   English   中英

C#ApiController HttpPost

[英]C# ApiController HttpPost

我試圖使我的API在我的C#控制台應用程序中工作。 我定義了一些控制器:

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);

        }

第二個按鈕可以正常工作。 它確實返回值,並且工作正常。 但是,第一個按鈕不起作用。 它說由於某種原因找不到特定的方法。

我究竟做錯了什么?

我認為您需要利用我喜歡的所謂的請求模型

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

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

這允許對請求正文進行反序列化和正確綁定。

WebApi控制器操作對其收到的參數非常敏感。 我很確定它解析失敗:

("mapId", 100000000);

到int mapId

確保正確使用了AddParameter方法。

您需要用斜杠分隔控制器/動作。

request.Resource = "character/Count";

另外,您指定了無效的操作名稱:

 request.Resource = "character/OnlineCount";

沒有方法“ OnlineCount”

首先,CharacterController不能在內部使用,簡單類型參數(例如:int,long ...)從url查詢中獲取值,RestSharp將mapId張貼在正文中,這就是mvc找不到動作的原因。 您可以像這樣標記mapId: ([FromBody]int mapId) ,或在網址中傳遞mapID,例如:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM