Andrew Volodko
Andrew Volodko

Reputation: 131

How to send form-data POST request with the help HttpClient with just Key-Value parameters

How can I to send a form-data POST request with the help of HttpClient with just Key-Value parameters?

Here is my code of the method:

public async Task<HttpResponseMessage> MakePostAsync(string endpoint, string token, Dictionary<string, string> headers = null, KeyValuePair<string, string>[] parameters = null)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, endpoint);
            if (headers != null)
            {
                foreach (var header in headers)
                    request.Headers.Add(header.Key, header.Value);
            }
            request.Headers.Add("Content-Type", "multipart/form-data");
            var formaData = new MultipartFormDataContent();

            formaData.Add(new StringContent(token), "__RequestVerificationToken");
            formaData.Add(new StringContent("admin"), "Username");
            formaData.Add(new StringContent("1"), "Password");
            request.Content = formaData;


            HttpResponseMessage response = await Task.Run(() => client.SendAsync(request));
            return response;
        }

The same request in the Postan on JavaScript, but it works

Upvotes: 5

Views: 4341

Answers (2)

Andrew Volodko
Andrew Volodko

Reputation: 131

This problem was resolved with the help of RestSharp. I needed to get Set-Cookie header value from the response of this request. And I just added CookieContainer to the RestClient. Not sure how to manage this problem with HttpClient. Thanks everybody who was trying to help.

Upvotes: 2

Leonardo
Leonardo

Reputation: 11391

You are not awaiting correctly.

Try: var response = await client.SendAsync(request);

Upvotes: 0

Related Questions