在 C# HttpClient 中发送表单数据

enter image description here 您好,我正在使用 C# HttpClient 从 api 中提取数据。我需要使用 post 方法以表单数据形式提取数据。我写了下面的代码,但得到了一个空的响应。我该怎么做?

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;
stack overflow Send form-data in C# HttpClient
原文答案
author avatar

接受的答案

您使用 FormUrlEncodedContent 以错误的方式发送数据。

要将您的参数作为 MultipartFormDataContent 字符串值发送,您需要替换以下代码:

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

有了这个:

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

答案: