问题
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?
回答1:
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;
}
来源:https://stackoverflow.com/questions/35322846/how-to-read-parse-content-from-oknegotiatedcontentresult