HttpClient SendAsync方法

时间:2018-08-28 13:27:51

标签: c# httpclient

我正在尝试向具有JSON内容的webapi发送删除请求。我搜索了,结果是Httpclient.DeleteAsync方法不能与内容一起使用,因此我必须使用Httpclient.SendAsync。但我无法成功做到这一点。我一直坚持采取400 statusCoded错误。我的代码是;

   public async Task<TResponse> DeleteWithContent(string requestPath, string jsonContent, string token)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(_apiUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            var contentType = new MediaTypeWithQualityHeaderValue("application/json");
            client.DefaultRequestHeaders.Accept.Add(contentType);



            if (!string.IsNullOrEmpty(token))
            {
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            }

            var httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");


            var request = new HttpRequestMessage(HttpMethod.Delete, client.BaseAddress);
            request.Content = httpContent;
           var response1= client.SendAsync(request).Result;

            var readed = response1.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<TResponse>(response1.ToString());
        }
    }

请帮助!

0 个答案:

没有答案