在 C# HttpClient 中发送表单数据

aht*_*a14 3 c# rest httpclient

在此输入图像描述您好,我正在使用 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;
Run Code Online (Sandbox Code Playgroud)

Cod*_*und 9

您使用 的方式发送数据的方式不正确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")
});
Run Code Online (Sandbox Code Playgroud)

有了这个:

content.Add(new StringContent("myvalue1"), "key1");
content.Add(new StringContent("myvalue2"), "key2");
content.Add(new StringContent("myvalue3"), "key3");
Run Code Online (Sandbox Code Playgroud)