为什么没有将详细的错误消息传递给HttpClient?

时间:2016-10-24 10:23:46

标签: c# asp.net-web-api httpclient

我正在使用自动生成的默认Web Api控制器。我正在测试客户端的验证和错误处理。但不知何故,我已经意识到细节错误消息没有传递给客户端。如果我在两种情况下都抛出HttpResponseException或返回IHttpActionResult,则客户端只会看到" Bad Request"但不是详细的消息。谁能解释一下出了什么问题呢?

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

客户端代码如下:

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

以上都不起作用??

THX

2 个答案:

答案 0 :(得分:0)

将以下代码替换为Web API删除操作。使用HttpResponseMessage作为api的返回tpye而不是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
            }
        }

客户端:

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

以上代码正在我这边工作。

答案 1 :(得分:0)

在您的客户端更改Console.WriteLine(response.ReasonPhrase);

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

它会给出详细的错误信息。