【问题标题】:WebApi: Reading errorsWebApi:读取错误
【发布时间】:2015-08-19 06:27:48
【问题描述】:

我有一个从 mvc 项目中使用的简单 web api,我不断收到“响应状态代码不表示成功”,我想知道如何从错误中获取响应正文,我可以看到休息查看器中的错误,但无法导航到错误。这是 MVC 应用程序中的以下代码

public ActionResult Index()
    {

        try
        {
            var uri = "http://localhost:57089/api/values";

            using (var client = new HttpClient())
            {
                Task<string> response =  client.GetStringAsync(uri);

                object result = JsonConvert.DeserializeObject(response.Result);

                return (ActionResult) result;

            }


        }
        catch (Exception ex)
        {
            return Content(ex.ToString());
        }

        return View();
    }

在 API 控制器中我发送了一个错误的请求,这是代码

        public IHttpActionResult Get()
        {

        return BadRequest("this is a very bad request " + System.DateTime.Now.ToUniversalTime());

        }

我尝试使用 WebException、HttpRequestException 作为异常来捕获错误,但没有成功。

我可以在其余查看器中看到响应正文

我希望能够导航到错误消息,以便将其传递给客户端(稍后将更改为 guid)。

[编辑]

我有一个不使用 GetStringAsync 的解决方案,但如果可能的话,我想使用它。

解决办法

 var httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri(url);
            HttpResponseMessage responseMessage = httpClient.GetAsync("").Result;

            if (responseMessage.IsSuccessStatusCode) return Content(responseMessage.ToString());
            var a = responseMessage.Content.ReadAsStringAsync().Result;

            var result = JsonConvert.DeserializeObject<HttpError>(a);

            object value = "";

            return Content(result.TryGetValue("ErrorMessage", out value) ? value.ToString() : responseMessage.ToString());

有没有更好的办法?

【问题讨论】:

    标签: model-view-controller asp.net-web-api asp.net-mvc-5


    【解决方案1】:

    使用WebException,您应该能够访问ResponseStream 和自定义错误消息,如下所示:

    catch (WebException e)
    {
        var message = e.Message;
        using (var reader = new StreamReader(e.Response.GetResponseStream()))
        {
            var content = reader.ReadToEnd();
        }
    }
    

    希望对您有所帮助。

    【讨论】:

    • 嗨大卫,不幸的是,我试过使用 webexception、AggregateException、HttpRequestException 它在 AggregateException 上中断,但没有关于错误的信息。
    • 我用另一种方式工作,不使用 GetStringAsync,虽然我更喜欢使用 GetStringAsync。
    • 你应该发布你的解决方案。
    • 我已经为这个问题发布了我的解决方案,想知道是否有更好的方法使用 GetStringAsync。
    猜你喜欢
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 2012-11-11
    • 2019-12-25
    • 2016-01-31
    相关资源
    最近更新 更多