在C# HttpClient中发送表单数据

3

enter image description here你好,我正在使用C# HttpClient从api中拉取数据。我需要使用post方法以form-data的形式获取数据。我编写了下面的代码,但是得到了一个空响应。我该怎么做呢?

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;

什么是 API 路径?您可以发布一下您的 API 吗? - Serge
1个回答

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")
});

使用这个:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接