如何 read/parse 来自 OkNegotiatedContentResult 的内容?
How to read/parse Content from OkNegotiatedContentResult?
在我的一个 API 操作 (PostOrder
) 中,我 可能 在 API (CancelOrder
).两个 return 一个 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; }
}
我需要的是 reading/parsing 来自 CancelOrder
的 ResultOrderDTO
响应,这样我就可以将其用作 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
),如图所示在下图中:
但是 cancelResponse.Content
不存在(或者至少在我对其他内容做出回应之前我无法访问它)而且我不知道如何 read/parse 这个 Content
。有什么想法吗?
只需将响应对象转换为 OkNegotiatedContentResult<T>
。内容 属性 是类型 T 的对象。在您的情况下是 ResultOrderDTO
.
的对象
if (cancelResponse is OkNegotiatedContentResult<ResultOrderDTO>)
{
// Here's how you can do it.
var result = cancelResponse as OkNegotiatedContentResult<ResultOrderDTO>;
var content = result.Content;
}
在我的一个 API 操作 (PostOrder
) 中,我 可能 在 API (CancelOrder
).两个 return 一个 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; }
}
我需要的是 reading/parsing 来自 CancelOrder
的 ResultOrderDTO
响应,这样我就可以将其用作 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
),如图所示在下图中:
但是 cancelResponse.Content
不存在(或者至少在我对其他内容做出回应之前我无法访问它)而且我不知道如何 read/parse 这个 Content
。有什么想法吗?
只需将响应对象转换为 OkNegotiatedContentResult<T>
。内容 属性 是类型 T 的对象。在您的情况下是 ResultOrderDTO
.
if (cancelResponse is OkNegotiatedContentResult<ResultOrderDTO>)
{
// Here's how you can do it.
var result = cancelResponse as OkNegotiatedContentResult<ResultOrderDTO>;
var content = result.Content;
}