投射到正确的类型?

时间:2015-02-11 11:03:15

标签: c# asp.net-web-api

我有以下WebApi操作:

    public async Task<IHttpActionResult> PostCustomer(DTO.Customer customer)
    {
        try
        {
            //Save in Db here...
            return Ok(customer);
        }
        catch (ValidationException<CustomerError> vex)
        {
            return ResponseMessage(Request.CreateResponse(HttpStatusCode.Conflict, vex));
        }
        catch (DatabaseException dex)
        {
            return ResponseMessage(Request.CreateResponse(HttpStatusCode.Conflict, dex));
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }

该操作可以返回更新的客户dto或不同的异常(ValidationException和DatabaseException是自定义异常)。

我有一个通用请求类,使用以下Save方法:

    public virtual T Save(T current)
    {
        response = client.PostAsJsonAsync<T>(updateUrl, current).Result;

        return Response();
    }

    private T Response()
    {
        if (response.IsSuccessStatusCode)
        {
            var result = response.Content.ReadAsAsync<T>().Result;
            original = result.DeepCopy<T>();

            return result;
        }

        else
        {
            dynamic e = response.Content.ReadAsAsync<ExpandoObject>().Result;
           //throw ??
        }
    }

要测试代码,我将内容读作ExpandoObject,但显然这不是正确的解决方案。

如何知道响应有什么类型的异常,以便我可以将正确的异常转发/转发给调用表单?

1 个答案:

答案 0 :(得分:0)

使用HttpResponseMessage.EnsureSuccessStatusCode

https://msdn.microsoft.com/en-us/library/system.net.http.httpresponsemessage.ensuresuccessstatuscode%28v=vs.118%29.aspx

try
{
    response.EnsureSuccessStatusCode();
    // Handle success
}
catch (HttpRequestException)
{
    // Handle failure
}