使用 ReadAsStringAsync() 时如何处理 Http 状态代码

How to handle Http Status code when making use of ReadAsStringAsync()

我有一个 JavaScript 客户端,它对 .net 服务进行 Ajax 调用(我们称之为第一个服务)。然后,第一个服务调用另一个 .net 控制器(称为第二个服务)。在这个控制器中,我抛出了一些异常。在第一行我说:

//来自第二个服务的代码

[HttpPost]
public HttpResponseMessage Results(ParamsModel data)
{
    throw new Exception("Exception for testing purpose");

}

//第一个服务的代码

    [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");

    }

问题:虽然第二个服务抛出错误并 returning 500 状态代码,但第一个服务 returns 200 状态代码到 JavaScript 客户端。我也无法读取由第二个服务编辑的状态代码 return,因为我只得到字符串输出。

求推荐。我想return 500状态码出现错误的时候.

为什么不能做一个异步动作方法?

[HttpPost]
public async Task<ActionResult> Results(ParamsModel data)
{
    try
    {
        var client = new HttpClient();
        var response = await client.PostAsJsonAsync(urlTemplate, data);
        var json = await response.Content.ReadAsStringAsync()
        return Content(result, "application/json");
    }
    catch(WebException ex)
    {
        //do note that the Response property might be null due to
        // connection issues etc. You have to handle that by yourself.
        var remoteErrorCode = ((HttpWebResponse)ex.Response).StatusCode;
        Request.CreateErrorResponse(remoteErrorCode, "An error just happened");
    }
}

但问题是,对于第一种方法的布局,在第二种方法中如何处理异常并不重要,因为第一种总是 return "Internal Server Error".

为了使其有用,您通常也应该 return 在第一种方法中使用不同的错误代码。

您可以在 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.
}

希望对您有所帮助。

您可以 return 像这样的 HttpResponseException:

[HttpPost]
public ActionResult Results(ParamsModel data)
{
    try
    {   
        var client = new HttpClient();
        var task = client.PostAsJsonAsync(urlTemplate, data);
        var result = task.Result.Content.ReadAsStringAsync().Result;

        return Content(result, "application/json");
    }
    catch (HttpResponseException ex)
    {
            return new HttpStatusCodeResult(ex.Response.StatusCode);
    }
}

您需要从 WebAPI 控制器中抛出正确的异常:

[HttpPost]
public HttpResponseMessage Results(ParamsModel data)
{
    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}

有几种状态码可以抛出:

https://msdn.microsoft.com/en-us/library/system.net.httpstatuscode.aspx