在我的一个 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; }
}
我需要的是读取/解析来自 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
不存在(或者至少在我对其他内容做出回应之前我无法访问它)并且我不知道如何阅读/解析它内容
。有什么想法吗?
最佳答案
只需将响应对象转换为 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;
}
关于c# - 如何从 OkNegotiatedContentResult 读取/解析内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35322846/