HttpClient没有发布表单数据 [英] HttpClient is not posting form data

查看:91
本文介绍了HttpClient没有发布表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我为什么HttpClientPostAsync没有发布表单数据?

Can anyone tell me why is the PostAsync of the HttpClient is not posting the form data?

在发布此客户端时,服务器端没有任何数据.上次我检查时,formFields包含键-值对中的数据,但无法在formContent中找到数据.

I'm getting no data on the server side at the time of this client posting. Last time I checked, the formFields contains data in key-value pairs but not able to find data in formContent.

using (var client = new HttpClient())
{
    var formFields = new List<KeyValuePair<string, string>>();

    formFields.Add(new KeyValuePair<string, string>("AccountId", _dealerAccountId));
    formFields.Add(new KeyValuePair<string, string>("Username", _dealerUsername));
    formFields.Add(new KeyValuePair<string, string>("Password", _dealerPassword));

    var formContent = new FormUrlEncodedContent(formFields);
    var response = await client.PostAsync(httpPrefix + "://" + httpHost + "/WebApi/Token/GetToken_v1/1592673/", formContent);
    if (!response.IsSuccessStatusCode)
    {
        return;
    }
    var responseContent = await response.Content.ReadAsStringAsync();

    token = JsonConvert.DeserializeObject<string>(responseContent);
}

推荐答案

我隐约记得有一个类似的问题.我们最终没有使用"PostAsync"方法,而是使用了以下方法.这是我们用来测试WebAPI的辅助方法.希望这会有所帮助.

I vaguely remembering having a similar issue. We ended up not using the "PostAsync" method but used the following. This is a helper method we use for testing our WebAPI. Hope this helps.

public async Task<TestHttpResponseMessage> Post(string url, string jsonPayload = "", Dictionary<string, string> headers = null, IFilter filter = null, HttpContent content = null)
{
    using (var server = CreateTestserver(filter))
    {
        if (!url.StartsWith("http"))
            url = "http://localhost/" + url;

        var request = new HttpRequestMessage
        {
            RequestUri = new Uri(url),
            Method = HttpMethod.Post,
            Content = content ?? new StringContent(jsonPayload, Encoding.UTF8, "application/json")
        };

        request.Headers.Add("usertoken", OpenApiApplication.TestApiKey.ToString());

        if (headers == null)
            headers = new Dictionary<string, string>();

        foreach (var header in headers)
            request.Content.Headers.Add(header.Key, header.Value);

        var httpResponseMessage = await server.HttpClient.SendAsync(request);

        var stringResult = await httpResponseMessage.Content.ReadAsStringAsync();

        return new TestHttpResponseMessage { JsonObject = Json.Decode(stringResult), HttpResponseMessage = httpResponseMessage };
    }
}

这篇关于HttpClient没有发布表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆