how to consume a web api, from


I have my Web API in ASP.NET , I need to make a simple abml consuming the services from the MVC driver. Could you help me? The WEB API that I have is the one that generates scaffolding

asked by c.c 16.08.2016 в 16:25

1 answer


For that you must use the class HttpClient

For example to make a GET


Note: Example adapted from: Calling to Web API From a .NET Client in ASP.NET Web API 2

public Task<Product> GetProduct(int id)
    using (var client = new HttpClient())
        client.BaseAddress = new Uri("http://url-base-del-api");
        // Agrega el header Accept: application/json para recibir la data como json  
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        // Hace la llamada a http://url-base-del-api/api/products/<id>
        var response = await client.GetAsync("api/products/" + id);

        // Si el servicio responde correctamente
        if (response.IsSuccessStatusCode)
            // Lee el response y lo deserializa como un Product
            return await response.Content.ReadAsAsync<Product>();
        // Sino devuelve null
        return Task.FromResult<Product>(null);
answered by 17.08.2016 / 06:35