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

标签 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; }
}

我需要的是读取/解析来自 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)如下图所示:

Debugger

但是 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/

相关文章:

c# - while语句中的三元表达式在每个循环中都被评估

c# - XNA - 矩阵等效于 SpriteBatch.Draw 转换?

javascript - 让我摆脱 JavaScript 回发故障船

c# - 使用 ASP.NET 3.5 C# 将 iPhone 重定向到另一个 URL

mysql - Azure Mysql HTTP REST API 。获取 JSON Web token

java - 有条件地忽略特定属性 DTO

security - 如何使我的 API 私有(private)但可由移动应用程序使用?

c# - 确定一个类是否被引用 C#

c# - 创建 app.config 文件

javascript - 单击时使用 javascript 禁用 aspx 中的按钮并从代码隐藏中启用它