问题描述
我有一个JavaScript客户端,这使得Ajax调用一个.NET服务(让我们把它叫做第一服务)。第一个服务,然后使得调用其他.NET控制器(称之为第二个服务)。在此控制器,我抛出一些异常。在第一行,我说:
I have a JavaScript client which makes Ajax call to a .net service (Lets call it First service). First service then makes call to another .net Controller (Call it Second Service). In this controller, I am throwing some exception. On the first line I am saying:
从第二个服务 // code
[HttpPost]
public HttpResponseMessage Results(ParamsModel data)
{
throw new Exception("Exception for testing purpose");
}
从第一服务 // code
[HttpPost]
public ActionResult Results(ParamsModel data)
{
var client = new HttpClient();
var task = client.PostAsJsonAsync(urlTemplate, data);
var result = task.Result.Content.ReadAsStringAsync().Result;
return Content(result, "application/json");
}
问题:虽然第二个服务抛出的错误和放大器;返回500状态code,第一servcie返回200状态code到JavaScript客户端。我也无法读取第二个服务返回我只得到字符串输出萨特斯code。
Problem: Though the Second Service is throwing error & returning 500 status code, The first servcie returns 200 status code to the JavaScript client. I am also not able to read the satus code returned by Second service as I only get string output.
请建议。我想回到 500状态code时出现错误
推荐答案
您可以实现的错误处理在如下HttpClient的。
You can implement error handling as follows in the HttpClient.
if (!task.Result.IsSuccessStatusCode)
{
if (task.Result.StatusCode == HttpStatusCode.InternalServerError)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "An error has occured.");
}
else
{
// Check for other status codes and handle the responses
}
}
else
{
// Success status code. Return success response.
}
希望这有助于。
这篇关于如何利用ReadAsStringAsync时处理HTTP状态code()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!