如何将复杂数据发送到控制器端点

How to send complex data to controller endpoint

我有这个基本案例:

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

您可以为负载创建一个模型class

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 方法,例如 here。使用 HttpClient:

using (var client = new HttpClient())
{
    var response = await client.PostAsync(
    "http://yourUrl", 
     new StringContent(json, Encoding.UTF8, "application/json"));
}

如果您的变量(日期、valueController 和修饰符)类型正确,则以下代码应该有效。

  var json = JsonConvert.SerializeObject(new { date:date, value : valueCollection.ToArray(), modifier:modifier });