我想将一个类作为参数传递给我的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?
答案 0 :(得分:1)
PostAsJsonAsync
将在请求中以ClusteringObject
的身份发送Body
,建议您尝试
FromBody
就像
public string Post([FromBody]ClusteringObject _cluesteringObject)