【问题标题】:How to read/parse Content from OkNegotiatedContentResult?如何从 OkNegotiatedContentResult 读取/解析内容?
【发布时间】:2016-05-21 06:08:42
【问题描述】:

在我的一个 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; }
}

我需要读取/解析来自CancelOrderResultOrderDTO 响应,以便我可以将其用作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。有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

    只需将响应对象转换为OkNegotiatedContentResult&lt;T&gt;。 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;
    }
    

    【讨论】:

    • 不敢相信我没有尝试过。谢谢。
    猜你喜欢
    • 2018-05-14
    • 2010-12-23
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2019-06-10
    • 1970-01-01
    相关资源
    最近更新 更多