0

I am trying to do send a delete request to webapi with a json content. I searched and the result is that Httpclient.DeleteAsync method cant be used with content so i have to use Httpclient.SendAsync. But i couldnt manage to success that. I always keeping to take 400 statusCoded error. My Code is;

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

Please help!!

rmznbyk 1
  • 1,104
  • 2
  • 13
  • 27
  • `var readed = response1.Content.ReadAsStringAsync();` this is wrong, you're missing an `await` or in your case a `.Result` because your in a sync method – Callum Linington Aug 28 '18 at 13:30
  • Or u can just extend 'var readed = response1.Content.ReadAsStringAsync().GetAwaiter().GetResult();' – J.Memisevic Aug 28 '18 at 13:32
  • 1
    400-level errors typically mean *your request is bad*. You haven't provided enough information for us to help with this, and it's odd that a `DELETE` request requires a body. – Dan Wilson Aug 28 '18 at 13:37
  • Do you control the other endpoint? It *should* probably ignore the delete body, but it *may* not. https://stackoverflow.com/questions/299628/is-an-entity-body-allowed-for-an-http-delete-request – ste-fu Aug 28 '18 at 14:15
  • @DanWilson that 'DELETE' take 2 integer and the error i have is "exceptionType":"System.ComponentModel.DataAnnotations.ValidationException" – rmznbyk 1 Aug 29 '18 at 05:25

0 Answers0