0

I want to post data to a REST API, but it does not create the correct request:

using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Accept", "text/csv");
HttpResponseMessage response = null;

string baseUrl = ServiceUrl + "/api/v25/upload/test";

Dictionary<string, string> parameters = new Dictionary<string, string>();

parameters.Add("field1", "value1");
parameters.Add("field2", "value2");

MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent content = new StringContent("long text...");
content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
HttpContent fields = new FormUrlEncodedContent(parameters);
form.Add(content, "message");
form.Add(fields);

response = client.PostAsync(baseUrl, form).Result;
var message = response.Content.ReadAsStringAsync().Result;
}

It makes this URL:

POST /api/v25/upload/test HTTP/1.1

and this would be the correct address:

POST /api/v25/upload/test?field1=value1&field2=value2 HTTP/1.1

Where is the error in code, please?

Kaj
  • 806
  • 6
  • 16
Sándor Hatvani
  • 435
  • 1
  • 7
  • 21

1 Answers1

1

HttpClient doesn't have an API that lets you build a query string. See Build query string for System.Net.HttpClient get for code that does that using HttpUtility.ParseQueryString.

Or use RestSharp instead:

var request = new RestRequest("/api/v25/upload/test", Method.POST);
request.AddParameter("field1", "value1", ParameterType.UrlSegment);
CodeCaster
  • 147,647
  • 23
  • 218
  • 272