Pra*_*bhu 4 .net c# asp.net-mvc asp.net-mvc-4 asp.net-web-api
我的WebAPI方法返回错误响应:
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Something bad happened");
Run Code Online (Sandbox Code Playgroud)
在我的客户端(一个MVC项目)上,我想显示错误消息,但是无法显示消息“发生了不好的事情”:
var response = await client.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
ViewBag.Error= response.ReasonPhrase;
}
Run Code Online (Sandbox Code Playgroud)
除了ReasonPhrase,我试过response.ToString(),response.Content.ToString()和response.Content.ReadAsStringAsync()。他们都没有收到我的消息。Postman如何显示消息?
有什么想法可以访问消息字符串吗?
如果您的回复内容返回为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"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2845 次 |
| 最近记录: |