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:
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?
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.
Represents an action result that performs content negotiation and returns an HttpStatusCode. OK response when it succeeds. Namespace: System.Web.Http.Results.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With