如何将 class 作为参数传递给 Web Api
How to pass a class as parameter to Web Api
我想将 class 作为参数传递到我的网站 API。这是我的代码:
网络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; }
}
我的 post 操作 returns 0。看来,我无法将我的对象传递给 Web API 这就是它显示每个属性的默认值的原因。如何将 ClusteringObject 的实例传递到我的 Web API?
PostAsJsonAsync
会在请求中发送 ClusteringObject
作为 Body
,我建议你试试
FromBody
喜欢
public string Post([FromBody]ClusteringObject _cluesteringObject)
我想将 class 作为参数传递到我的网站 API。这是我的代码:
网络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; }
}
我的 post 操作 returns 0。看来,我无法将我的对象传递给 Web API 这就是它显示每个属性的默认值的原因。如何将 ClusteringObject 的实例传递到我的 Web API?
PostAsJsonAsync
会在请求中发送 ClusteringObject
作为 Body
,我建议你试试
FromBody
喜欢
public string Post([FromBody]ClusteringObject _cluesteringObject)