Sonu K
Sonu K

Reputation: 2802

How to consume ASP.NET Web API in C# which returns an object

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.

Upvotes: 2

Views: 2291

Answers (1)

goobering
goobering

Reputation: 1553

Try:

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

    var postedProduct = await response.Content.ReadAsAsync<Product>();
}

Upvotes: 3

Related Questions