0

Using WebClient do send an array to an ApiController via query string I get the error 400.

The api method looks like

public IHttpActionResult List([FromUri] Model model)

In the Model class I have

public int[] Ids { get; set; }

In the client side the code looks like:

webClient.QueryString.Add("ids", "1");
webClient.QueryString.Add("ids", "2");
...
await webClient.DownloadStringTaskAsync(url);

If I send just one "ids" parameter the code works fine, but not with two or more.

I found that the client creates the url like "url?ids=1,2" instead "url?ids=1&ids=2".

Is there some configuration I missed?

5
  • Is Ids your only property inside your model? Commented Aug 14, 2020 at 13:49
  • Which version is this of Asp.Net Core? Commented Aug 14, 2020 at 13:50
  • I think the problem is that ASP.NET doesn't create GET strings with duplicate key names per default. You could try to manually generate a GET URL
    – Moray
    Commented Aug 14, 2020 at 13:53
  • I'm using .Net 4.6, not Core. Yes @Moray but it's strange that Api don't work with WebClient in the same .Net version. If I create the query string by hand it works. Commented Aug 14, 2020 at 13:55
  • I found that is required code this solution out of the box: stackoverflow.com/questions/9981330/… Commented Aug 14, 2020 at 13:57

1 Answer 1

1

WebClient will automatically turn multiple values with the same key into a comma separated string. You can change this behavior, see: How to build WebClient querystring with duplicate keys?

I would recommend using HttpClient instead of WebClient though.

1
  • Completly agree with using HttpClient instead of the legacy WebClient Commented Aug 14, 2020 at 14:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.