2

I have one requirement in which I am returning an object from a Web API method, what I want to do is to consume the returned object in my C# code something like this:

WEB API Method:

public Product PostProduct(Product item)
{
    item = repository.Add(item);
    var response = Request.CreateResponse<Product>(HttpStatusCode.Created, item);

    string uri = Url.Link("DefaultApi", new { id = item.Id });
    response.Headers.Location = new Uri(uri);

    return item;
}

C# code that consumes the API:

Public Product AddProduct()
{    
    Product gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };

    //
    //TODO: API Call to POstProduct method and return the response.
    //

}

Any suggestions on this?

I have an implementation for this but it is returning an HttpResponseMessage, but I want to return the object, not the HttpResponseMessage.

public HttpResponseMessage PostProduct(Product item)
{
    item = repository.Add(item);
    var response = Request.CreateResponse<Product>(HttpStatusCode.Created, item);

    string uri = Url.Link("DefaultApi", new { id = item.Id });
    response.Headers.Location = new Uri(uri);

    return response;
}

Code consuming the API:

using (HttpClient client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:9000/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };

    HttpResponseMessage response = await client.PostAsJsonAsync("api/products", gizmo);

    var data = response.Content;

    if (response.IsSuccessStatusCode)
    {
        // Get the URI of the created resource.
        Uri gizmoUrl = response.Headers.Location;
    }
}

Here the code segment:

HttpResponseMessage response = await client.PostAsJsonAsync("api/products", gizmo);

returns the HttpResponseMessage but i dont want this, I want to return the Product object.

4
  • 1
    use httpclient in C# Commented Mar 4, 2015 at 9:39
  • 3
    tr y use response.Content.ReadAsAsync<TResult>().Result where TResult is your expected return type. Commented Mar 4, 2015 at 9:47
  • try just doing: Request.CreateResponse(HttpStatusCode.OK, item , new JsonMediaTypeFormatter()); Commented Mar 4, 2015 at 11:34
  • @FrebinFrancis - These approaches are working asynchronously, is there a way to do the same in as synchronous way? I just wanted to make sure if the request is processed and do some stuff once the response is received or it is timed out. Won't it be a good idea to wait for a response for a certain period of time and proceed either if a response a received or it times out. Commented Mar 5, 2015 at 13:08

1 Answer 1

3

Try:

if (response.IsSuccessStatusCode)
{
    // Get the URI of the created resource.
    Uri gizmoUrl = response.Headers.Location;

    var postedProduct = await response.Content.ReadAsAsync<Product>();
}
Sign up to request clarification or add additional context in comments.

4 Comments

These approaches are working asynchronously, is there a way to do the same in as synchronous way?
Not, as far as I'm aware, while using an HttpClient. I'm not at all sure that it would be a good idea to use a synchronous method here. There's absolutely no way of knowing how long the call will take to return, or even if it'll return at all. If you use a synchronous method you're going to block your thread in the meantime.
But my point is I just wanted to make sure if the request is processed and do some stuff once the response is received or it is timed out. Won't it be a good idea to wait for a response for a certain period of time and proceed either if a response a received or it times out.
That's pretty much how the async/await pattern works. Your code runs synchronously up until you call an asynchronous method using the 'await' marker. It runs your asynchronous method in the background and returns control to the main thread so that your UI remains responsive. Whenever your async call completes, the remainder of your code runs. If you have questions about how to use async/await to make best use of the code in the answer I'd recommend starting a new question, or reviewing some of the many already posted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.