Why detailed error message is not passed to HttpClient?

11,205

In your client side change Console.WriteLine(response.ReasonPhrase);

to Console.WriteLine(response.Content.ReadAsStringAsync().Result);

and it will give the detailed error message.

Share:
11,205
user1829319
Author by

user1829319

Updated on July 24, 2022

Comments

  • user1829319
    user1829319 almost 2 years

    I am using the default Web Api controller that is auto generated. I am testing the validation and error handling in the client side. But somehow I have realised that the detail error message is not passed to client. Either if I throw HttpResponseException or returning IHttpActionResult in both cases the client is seeing only "Bad Request" but not the detailed message. Can anyone explain what is going wrong please?

         public IHttpActionResult Delete(int id)
        {
            if (id <= 0)
            {
                var response = new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content = new StringContent("Id should be greater than zero.", System.Text.Encoding.UTF8, "text/plain"),
                    StatusCode = HttpStatusCode.NotFound
    
                };
                throw new HttpResponseException(response) // Either this way
            }
    
            var itemToDelete = (from i in Values
                                where i.Id == id
                                select i).SingleOrDefault();
    
            if (itemToDelete == null)
            {
                return BadRequest(string.Format("Unable to find a value for the Id {0}", id)); // Or This way
            }
    
            Values.Remove(itemToDelete);
            return Ok();
        }
    

    client code is as:

     private async static Task DeleteValue(int id)
        {
    
            var url = "http://localhost:13628/api/Values/" + id;
            using (var client = new HttpClient())
            {
                var response = await client.DeleteAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    await ReadValues();
                }
                else
                {
                    Console.WriteLine(response.ReasonPhrase);
                    Console.WriteLine(response.StatusCode);
                }
            }
        }
    

    None of the above works??

    Thx