2

What is the preferred way for handling web api endpoints for each controller? For example, my MVC controller will be calling different endpoints. These are the only ones for now, but it could change.

Also, I will be developing this locally and and deploying to development server.

http://localhost:42769/api/categories/1/products

http://localhost:42769/api/products/

public class ProductsController : Controller
{
    HttpClient client;
    string url = "http://localhost:42769/api/categories/1/products"; //api/categories/{categoryId}/products

    public ProductsController()
    {
        client = new HttpClient();
        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }


    // GET: Products
    public async Task<ActionResult> ProductsByCategory()
    {
        HttpResponseMessage responseMessage = await client.GetAsync(url);
        if (responseMessage.IsSuccessStatusCode)
        {
            var responseData = responseMessage.Content.ReadAsStringAsync().Result;
            var products = JsonConvert.DeserializeObject<List<GetProductsByCategoryID>>(responseData);
            return PartialView(products);
        }

        return View("Error");
    }
}
Jason
  • 103
  • 1
  • 9
  • An old fashioned way is to use wcf http://stackoverflow.com/questions/13200381/asp-net-mvc-4-application-calling-remote-webapi/13207679#13207679 – peco Sep 26 '16 at 07:15

1 Answers1

2

Not sure I understand you question or problem, but I would create a wrapper class for the service and then have different methods for each resource that you need to call. Always think SOLID.

Example (written by hand)

public class Client
{
    private Uri baseAddress;

    public Client(Uri baseAddress)
    {
        this.baseAddress = baseAddress;
    }

    public IEnumerable<Products> GetProductsFromCategory(int categoryId)
    {
         return Get<IEnumerable<Product>>($"api/categories/{categoryId}/products");
    }

    public IEnumerable<Products> GetAllProducts()
    {
         return Get<IEnumerable<Product>>($"api/products");
    }

    private T Get<T>(string query)
    {
        using(var httpClient = new HttpClient())
        {
             httpClient.BaseAddress = baseAddress;

             var response= httpClient.Get(query).Result;
             return response.Content.ReadAsAsync<T>().Result;
        }
    }
}
Michael
  • 3,350
  • 2
  • 21
  • 35