简体   繁体   中英

C# ApiController HttpPost

I'm trying to make my API work in my C# console application. I've defined a few controllers:

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

        }
    }
}

Note that it takes mapId as a parameter.

I'm using RestSharp to test my API. Here's the code that executes the requests:

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

        }

The second button works fine. It does return the value and it works just fine. However, the first button does not work. It says it can't find the specific method for some reason.

What am I doing wrong?

I think you need to make use of what I like to call a Request Model .

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

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

This allows the request body to be deserialized and bound correctly.

WebApi controller actions are very sensitive to the parameters they receive. I'm pretty sure it fails at parsing this:

("mapId", 100000000);

to int mapId

Make sure you are using the AddParameter method correctly.

you need to separate your controller / action with a slash.

request.Resource = "character/Count";

also, you had in invalid action name specified:

 request.Resource = "character/OnlineCount";

There is no method 'OnlineCount'

first of all, CharacterController can't internal, the simple type parameter(eg:int, long...) gets value from the url query, RestSharp post the mapId in body, that's why mvc can't find the action. you can mark the mapId like this: ([FromBody]int mapId) , or pass the mapID in url like: character/SetMap?MapId=1000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM