我有一个基本情况:
[HttpPost("endpoint")]
public IActionResult Endpoint(DateTime date, string value, bool modifier)
{
return Ok($"{date}-{value}-{modifier}");
}
我可以用向它发送请求
var testContent = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "date", DateTime.Today.ToShortDateString() },
{ "value", "value1" },
{ "modifier", true.ToString() }
});
相反,我希望我的终点是这个,而不是
[HttpPost("endpointwithlist")]
public IActionResult EndpointWithList(DateTime date, List<string> value, bool modifier)
{
return Ok($"{date}-{value.FirstOrDefault()}-{modifier}");
}
我该如何发送?我试过下面的,没有什么工作
var json = JsonConvert.SerializeObject(new { date, value = valueCollection.ToArray(), modifier });
var testContentWithList = new ByteArrayContent(Encoding.UTF8.GetBytes(json));
testContentWithList.Headers.ContentType = new MediaTypeHeaderValue("application/json");
您可以为有效载荷创建一个模型类
public class EndpointWithListModel
{
public DateTime Date {get; set;}
public List<string> Value {get; set;}
public bool Modifier {get; set;}
}
则方法参数可以使用[FromBody]
属性
public IActionResult EndpointWithList([FromBody]EndpointWithListModel model)
然后将json发送到POST方法,示例如下。使用HttpClient
:
using (var client = new HttpClient())
{
var response = await client.PostAsync(
"http://yourUrl",
new StringContent(json, Encoding.UTF8, "application/json"));
}
如果您的变量(date、valueController和修饰符(的类型正确,那么下面的代码应该可以工作。
var json = JsonConvert.SerializeObject(new { date:date, value : valueCollection.ToArray(), modifier:modifier });