Search code examples
listasp.net-corepostparametershttpclient

Can not pass a list of strings to a Web API endpoint. Why?


Can not pass a list of strings to a Web API endpoint. Why?

Here is my controller:

[Route("[controller]")]
[ApiController]
public class MyController
{
    [HttpPost("foo")]
    public string MyMethod(List<string> strs)
    {
        return "foo";
    }
}

Here is how I am trying to call it:

var strs = new List<string> { "bar" };
var json = JsonConvert.SerializeObject(strs);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpCliet.PostAsync("/My/foo", content);

Before calling the endpoint I place a breakpoint on the return "foo"; line. Once the breakpoint is hit the strs list inside the MyController.MyMethod is empty. The strs is not null, but it contains no elements. While my intentions and expectations are to see the strs containing one element, i.e. the string "bar".

I am using the ASP.NET Core 2.2 in project where I create and use the HttpClient. And I am using the same ASP.NET Core 2.2 in project where I have the endpoint.

I am not sure what is wrong here. I have checked a few sources. E.g. the following:

C# HTTP post , how to post with List<XX> parameter?

https://carldesouza.com/httpclient-getasync-postasync-sendasync-c/

https://blog.jayway.com/2012/03/13/httpclient-makes-get-and-post-very-simple/

And I can not find what I am missing according to those resources.

UPDATE

The following call works for me as expected:

var json = JsonConvert.SerializeObject(string.Empty);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await server.CreateClient().PostAsync("/My/foo?strs=bar", content);

Maybe someone knows why the parameters in my case are read from the query string only, but not from body?


Solution

  • You can change your url to a full url in client.PostAsync.Here is a demo worked:

    Api(localhost:44379):

    WeatherForecastController:

    [HttpPost("foo")]
            public string MyMethod(List<string> strs)
            {
                return "foo";
            }
    

    Call(localhost:44326):

    public async Task<IActionResult> CheckAsync() {
                HttpClient client = new HttpClient();
                var strs = new List<string> { "bar","bar1","bar2" };
                var json = JsonConvert.SerializeObject(strs);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await client.PostAsync("https://localhost:44379/WeatherForecast/foo", content);
                return Ok(response);
            }
    

    result: enter image description here