如何从OkNegotiatedContentResult读取/解析内容?

时间:2016-02-10 18:12:35

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

在我的一个API操作(PostOrder)中,我可能正在使用API​​中的其他操作(CancelOrder)。两者都返回JSON格式的ResultOrderDTO类型,对于这两个操作都设置为ResponseTypeAttribute,如下所示:

public class ResultOrderDTO
{
    public int Id { get; set; }
    public OrderStatus StatusCode { get; set; }
    public string Status { get; set; }
    public string Description { get; set; }
    public string PaymentCode { get; set; }
    public List<string> Issues { get; set; }
}

我需要的是从ResultOrderDTO读取/解析CancelOrder响应,以便我可以将其用作PostOrder的响应。这就是我的PostOrder代码:

// Here I call CancelOrder, another action in the same controller
var cancelResponse = CancelOrder(id, new CancelOrderDTO { Reason = CancelReason.Unpaid });

if (cancelResponse is OkNegotiatedContentResult<ResultOrderDTO>)
{
    // Here I need to read the contents of the ResultOrderDTO
}
else if (cancelResponse is InternalServerErrorResult)
{
    return ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, new ResultError(ErrorCode.InternalServer)));
}

当我使用调试器时,我可以看到ResultOrderDTO它在响应中的某处(看起来像Content),如下图所示:

Debugger

但是cancelResponse.Content不存在(或者至少在我将响应转换为其他内容之前我无法访问它)并且我不知道如何读取/解析此{{1} }}。有什么想法吗?

1 个答案:

答案 0 :(得分:17)

简单地将响应对象强制转换为OkNegotiatedContentResult<T>。 Content属性是T类型的对象,在您的情况下是ResultOrderDTO的对象。

if (cancelResponse is OkNegotiatedContentResult<ResultOrderDTO>)
{
    // Here's how you can do it. 
    var result = cancelResponse as OkNegotiatedContentResult<ResultOrderDTO>;
    var content = result.Content;
}