CrazyCoder
CrazyCoder

Reputation: 2378

Getting the HttpResponseMessage Content value which is set manually(hard coded in the code)

I have a method in my application where I have to set the HttpResponseMessage response for some reason. This is my below code I have. There is class Order and OrderDetail.

         public void someMethod()
        {
            var response = await SendHttpResponse("123");
            Order objId = new Order();
            objId = JObject.Parse(await response.Content.ReadAsStringAsync()).ToObject<Order>();
            string item = objId.OrderDetail.LastOrDefault<item>().Status

        }

SendHttpResponse method, where the HttpResponseMessage is hardcoded.

public async Task<HttpResponseMessage> SendHttpResponse(string orderid)
{
    Task<Order> result = CreateOrder(orderid);
    string jsonString = JsonConvert.SerializeObject(result);
    return new HttpResponseMessage(HttpStatusCode.OK)
    { Content = new StringContent(jsonString) };// assuming something wrong with this conversion
}

I have an Order class and OrderDetail class.

public async Task<Order> CreateOrder(string OrderId)
{
    Order order = new Order();
    order.id = OrderId;
    order.date = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");

    OrderDetail od = new OrderDetail();
    od.item = "xyz";
    od.rate = 12;
    List<OrderDetail> lst = new List<OrderDetail>();
    lst.Add(od);
    order.OrderDetail = lst;
}

Now the problem I'm facing is, in SomeMethod, item is coming as null instead of xyz. When I debug this, I can see that CreateOrder method is executed without any exception and data is also converted to JSON format, but those values are not returned to SomeMethod properly. I'm assuming, the conversion I'm doing in SendHttpResponse is wrong and should be done differently.

Can any help me to correct this code? Many thanks!

Upvotes: 1

Views: 267

Answers (1)

kennyzx
kennyzx

Reputation: 12993

CreateOrder(orderid); returns a Task, not the Order object.

So you have to await it.

Order result = await CreateOrder(orderid); //

you also forget to return the order in the CreateOrder method.

you also forget to add async to public void someMethod().

So your code should not be compiled successfully.

Upvotes: 1

Related Questions