0

I have this basic case:

    [HttpPost("endpoint")]
    public IActionResult Endpoint(DateTime date, string value, bool modifier)
    {
        return Ok($"{date}-{value}-{modifier}");
    }

and I'm able to send a request to it with

    var testContent = new FormUrlEncodedContent(new Dictionary<string, string>
    {
        { "date", DateTime.Today.ToShortDateString() },
        { "value", "value1" },
        { "modifier", true.ToString() }
    });

Instead I want my endpoint to be this instead

    [HttpPost("endpointwithlist")]
    public IActionResult EndpointWithList(DateTime date, List<string> value, bool modifier)
    {
        return Ok($"{date}-{value.FirstOrDefault()}-{modifier}");
    }

How do I send this? I have tried the below, nothing works

    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");
robola
  • 975
  • 1
  • 6
  • 9

2 Answers2

2

You might create a model class for the payload

public class EndpointWithListModel
{
    public DateTime Date {get; set;}
    public List<string> Value {get; set;}
    public bool Modifier {get; set;}
}

the method parameter then could use [FromBody] attribute

public IActionResult EndpointWithList([FromBody]EndpointWithListModel model)

then send the json to your POST method, example is here. Using HttpClient:

using (var client = new HttpClient())
{
    var response = await client.PostAsync(
    "http://yourUrl", 
     new StringContent(json, Encoding.UTF8, "application/json"));
}
Martin Staufcik
  • 8,295
  • 4
  • 44
  • 63
  • This worked. I had actually tried this, but I was missing the [FromBody] attribute. – robola Apr 18 '20 at 07:19
  • Is there anyway to make it work if I can't change the endpoint? – robola Apr 18 '20 at 07:29
  • [FromBody] can be used also on simple parameters (strings, ints..), I do not know if it is possible to use multiple FromBody attributes in one method, probably not possible, there is only one body in the request. – Martin Staufcik Apr 18 '20 at 07:35
  • You're correct, from the microsoft docs, it shouldn't be passed to more than one parameter per method. Thanks for all your help. – robola Apr 19 '20 at 03:48
0

if your variables(date, valueController and modifier) are in the right type, following code should work.

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