Reputation: 465
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?
Upvotes: 0
Views: 671
Reputation: 151588
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);
Upvotes: 1