简体   繁体   中英

Calling a GetAll method from a Web Api from your C# client

I was looking at examples online and found a tutorial on retrieving products that uses a C# WEB API service and a C# console application as the client however, the tutorial defines a function in the service to get all products however, it does not tell you how to call it from the client:

public IEnumerable<Product> GetAllProducts()
{
    ...
}

The other CRUD methods declare using IHttpActionResult so I was confused how to call it.

So in my client I blindly attempted to call doing the following which is obviously incorrect:

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

    // HTTP GET ALL
    HttpResponseMessage response = await client.GetAsync("api/products");
    if (response.IsSuccessStatusCode)
    {
        List<Model.Product> products = await.response.Content.ReadAsAsync<IEnumerable<Model.Product>();
    }
}

This gives me a syntax error. So how do I code it them? Do I need to change the server or the client code or both?

For a single product the code is and this works:

// HTTP GET Specific Product
response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
    Model.Product product = await response.Content.ReadAsAsync<Model.Product>();        
}

and the server is:

public IHttpActionResult GetProduct(int id)
{
    var product = repository.GetByID(id);
    if (product != null)
        return Ok(product);
    else
        return NotFound();     
}
List<Model.Product> products = await.response.Content.ReadAsAsync<IEnumerable<Model.Product>(); 

You missed a closing > at the end. Correct:

var products = await.response.Content.ReadAsAsync<IEnumerable<Model.Product>>(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM