如何将类作为参数传递给Web Api

时间:2018-07-16 13:18:16

标签: rest asp.net-web-api asp.net-web-api2 asp.net-core-webapi

我想将一个类作为参数传递给我的Web API。这是我的代码:

Web API:

[Route("api/[controller]")]
public class ValuesController : Controller
{

    [HttpPost]
    public string Post(ClusteringObject _cluesteringObject)
    {

        return _cluesteringObject.NumberOfCluster.ToString();
    }


}
public class ClusteringObject
{
    public string Data { get; set; }

    public int NumberOfCluster { get; set; }

}

我的测试控制台应用程序代码:

  class Program
{
    static void Main(string[] args)
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:57961/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

        var testData = new ClusteringObject()
        {
            Data = "asdf",
            NumberOfCluster = 1
        };

        HttpResponseMessage response = client.PostAsJsonAsync("api/values", testData).Result;

        string res = "";
        using (HttpContent content = response.Content)
        {
            Task<string> result = content.ReadAsStringAsync();

            res = result.Result;
        }
    }
}

public class ClusteringObject
{
    public string Data { get; set; }

    public int NumberOfCluster { get; set; }

}

我的发布操作返回0。看来,我无法将对象传递给Web API,这就是为什么它显示每个属性的默认值。如何将ClusteringObject实例传递给Web API?

1 个答案:

答案 0 :(得分:1)

PostAsJsonAsync将在请求中以ClusteringObject的身份发送Body,建议您尝试 FromBody就像

public string Post([FromBody]ClusteringObject _cluesteringObject)