从桌面客户端调用Web API

时间:2018-07-30 09:13:06

标签: c# wpf

正在处理WPF项目。发送的请求类型为“ application / x-www-form-urlencoded”的内容类型,非常适合Web客户端。但是当请求从WPF项目发送时,其内容从API接收为空。

        public static string urlEncoded = "application/x-www-form-urlencoded";
        public static async Task<HttpResponseMessage> SendRequest(HttpMethod method, string endPoint, dynamic content = null)
        {
            HttpResponseMessage response = null;
            using (var client = new HttpClient())
            {
                using (var request = new HttpRequestMessage(method, endPoint))
                {
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(urlEncoded));
                    if (content != null)
                    {
                        string c;
                        if (content is string)
                            c = content;
                        else
                            c = JsonConvert.SerializeObject(content);
                        request.Content = new StringContent(c, Encoding.UTF8, urlEncoded);
                    }

                    response = await client.SendAsync(request).ConfigureAwait(false);
                }
            }
            return response;

        }

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

最后,我从中得到了解决方案。只是更改内容

var keyValues = new List<KeyValuePair<string, string>>()
{
   // Here Adding body
}
request.Content = new FormUrlEncodedContent(keyValues);

然后开始工作。