简体   繁体   中英

Calling Web API from Desktop Client

Working on a WPF project. A post request send with content type 'application/x-www-form-urlencoded' which were working nice for web client. But when request send from WPF project then its conten receive null from 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;

        }

Anyone can help me?

Finally I get a solution from this. Just changing content

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

Then its working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM