ahta14
ahta14

Reputation: 123

Send form-data in C# HttpClient

enter image description hereHello, I am pulling data from an api with C# HttpClient. I need to pull data in form-data form with the post method. I wrote the code below but got an empty response. How can I do it?

var client = new HttpClient();

        client.Timeout = TimeSpan.FromSeconds(300);
        client.DefaultRequestHeaders.Accept.Add(
    new MediaTypeWithQualityHeaderValue("application/json"));

    var request = new HttpRequestMessage();
        request.Method = HttpMethod.Post;
        request.RequestUri = new Uri("https://myapi.com");

        var content = new MultipartFormDataContent();
       
        var dataContent = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("value1", "myvalue1"),
            new KeyValuePair<string, string>("value2", "myvalue2"),
            new KeyValuePair<string, string>("value3", "myvalue3")
        });
        content.Add(dataContent);

        request.Content = content;
        var header = new ContentDispositionHeaderValue("form-data");
        request.Content.Headers.ContentDisposition = header;
        
        var response = await client.PostAsync(request.RequestUri.ToString(), request.Content);
        var result = response.Content.ReadAsStringAsync().Result;

Upvotes: 4

Views: 15515

Answers (1)

CodeNotFound
CodeNotFound

Reputation: 23220

You're sending your data in an incorrect way by using FormUrlEncodedContent.

To send your parameters as MultipartFormDataContent string values you need to replace the code below:

var dataContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("key1", "myvalue1"),
    new KeyValuePair<string, string>("key2", "myvalue2"),
    new KeyValuePair<string, string>("key3", "myvalue3")
});

With this:

content.Add(new StringContent("myvalue1"), "key1");
content.Add(new StringContent("myvalue2"), "key2");
content.Add(new StringContent("myvalue3"), "key3");

Upvotes: 10

Related Questions