Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read/parse Content from OkNegotiatedContentResult?

In one of my API actions (PostOrder) I may be consuming another action in the API (CancelOrder). Both return a JSON formatted ResultOrderDTO type, set as a ResponseTypeAttribute for both actions, which looks like this:

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

What I need is reading/parsing the ResultOrderDTO response from CancelOrder, so that I can use it as response for PostOrder. This is what my PostOrder code looks like:

// 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)));
}

When I use the debugger, I can see that the ResultOrderDTO it is there somewhere in the response (looks like the Content) as shown in the pic below:

Debugger

but cancelResponse.Content does not exist (or at least I don't have access to it before I cast my response to something else) and I have no idea about how to read/parse this Content. Any idea?

like image 330
Antrim Avatar asked Feb 10 '16 18:02

Antrim


People also ask

How do I get my status code from IHttpActionResult?

IHttpActionResult contains a single method, ExecuteAsync, which asynchronously creates an HttpResponseMessage instance. If a controller action returns an IHttpActionResult, Web API calls the ExecuteAsync method to create an HttpResponseMessage. Then it converts the HttpResponseMessage into an HTTP response message.

What is Oknegotiatedcontentresult?

Represents an action result that performs content negotiation and returns an HttpStatusCode. OK response when it succeeds. Namespace: System.Web.Http.Results.


1 Answers

Simply cast the response object to OkNegotiatedContentResult<T>. The Content property is object of type T. which in your case is object of ResultOrderDTO.

if (cancelResponse is OkNegotiatedContentResult<ResultOrderDTO>)
{
    // Here's how you can do it. 
    var result = cancelResponse as OkNegotiatedContentResult<ResultOrderDTO>;
    var content = result.Content;
}
like image 154
vendettamit Avatar answered Oct 12 '22 22:10

vendettamit