user1829319
user1829319

Reputation: 743

Why detailed error message is not passed to HttpClient?

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

Upvotes: 15

Views: 21617

Answers (2)

Buddhi Madarasinghe
Buddhi Madarasinghe

Reputation: 748

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

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

and it will give the detailed error message.

Upvotes: 24

Suyog
Suyog

Reputation: 181

Replace below code into Web API delete action. Use HttpResponseMessage as return tpye for api instead of IHttpActionResult

        [HttpDelete]
        [Route("{id:int:min(1)}")]
        public async Task<HttpResponseMessage> DeleteAsync(int id)
        {
            if(id < 0 )
            {
                return await Task.FromResult<HttpResponseMessage>(Request.CreateResponse<string>(HttpStatusCode.BadRequest, "Id should be greater than zero."));
            }
            try
            {
                var itemToDelete = (from i in Values
                                    where i.Id == id
                                    select i).SingleOrDefault();

                if (itemToDelete == null)
                {
                    return await Task.FromResult<HttpResponseMessage>(Request.CreateResponse<string>(HttpStatusCode.NotFound,
                                        string.Format("Unable to find a value for the Id {0}", id))); 
                }

                Values.Remove(itemToDelete);
                return await Task.FromResult<HttpResponseMessage>(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                 return Request.CreateResponse<string>(HttpStatusCode.InternalServerError, "Something went wrong."); // Default message if exception occured
            }
        }

And client Side:

        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
                {
                    var errorMessage = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(await response.Content.ReadAsStringAsync());
                    // Here Newtonsoft.Json Package is used to deserialize response content 
                    Console.WriteLine(errorMessage);
                    Console.WriteLine(response.StatusCode);
                }
            }
        }

Above code is working at my side.

Upvotes: 1

Related Questions