简体   繁体   English

如何从Request.CreateErrorResponse中读取错误消息?

[英]How to read the error message from Request.CreateErrorResponse?

My WebAPI method returns an error response: 我的WebAPI方法返回错误响应:

return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Something bad happened");

On my client end (an MVC project), I want to display the error message, but unable to get the message "Something bad happened" to display: 在我的客户端(一个MVC项目),我想显示错误消息,但无法显示消息“发生了错误”:

var response = await client.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
    ViewBag.Error= response.ReasonPhrase; 
}

Other than ReasonPhrase, I've tried response.ToString() , response.Content.ToString() , and response.Content.ReadAsStringAsync() . 除了ReasonPhrase之外,我还尝试了response.ToString()response.Content.ToString()response.Content.ReadAsStringAsync() None of them get me the message. 他们都没有得到我的信息。 How come Postman is able to display the message? Postman如何才能显示消息?

Any ideas how I can access the message string? 我有什么想法可以访问消息字符串?

If your response content comes back as application/json , you can deserialize it with Json.Net like this: 如果您的响应内容以application/json ,您可以使用Json.Net对其进行反序列化,如下所示:

if(!response.IsSuccessStatusCode)
{
    var errors = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(response.Content.ReadAsStringAsync().Result);
    var message = errors[HttpErrorKeys.MessageKey];

    // message is "Something bad happened"
}

I think response.Content.ReadAsStringAsync() returns a Task<string> , not a string . 我认为response.Content.ReadAsStringAsync()返回一个Task<string> ,而不是一个string You'd need to use 你需要使用

response.Content.ReadAsStringAsync().Result 

or if your method is marked async you can await it. 或者如果您的方法被标记为async您可以等待它。

string message = await response.Content.ReadAsStringAsync();

That's what I do to get error message. 这就是我收到错误消息的方法。 when you complete your debug, you can change return type 完成调试后,您可以更改返回类型

       public string someRequest()
    {
        try
        {
            var response = await client.SendAsync(request);
            return "Ok";
        }
        catch (Exception e)
        {
         return e.Message;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM