在我的一个API Action (PostOrder
)中,我可能正在使用API中的另一个 Action (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
),如下图所示:但是
cancelResponse.Content
不存在(或者至少在我对其他内容做出响应之前我没有访问它的权限),而且我不知道如何读取/解析此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/