Hello, there are some approaches, I’ll quote to what I think is most appropriate, which is using the HttpClient
.
If you do not find it in your project, install the following package.: System.Net.Http
public class MinhaController : Controller
{
// o HttpClient deve ter uma instancia estatica, para evitar ficar abrindo muitas portas.
private static HttpClient httpClient;
static MinhaController()
{
httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("https://api.pipedrive.com/v1/deals");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Se precisar adicionar alguma autenticação, faça o aqui.
}
public async Task<ActionResult> Index()
{
var stageId = GetStageFromSomewhere();
var token = GetTokenFromSomewhere();
var queryString = $"?stage_id={stageId}&status=all_not_deleted&start=0&api_token={token}";
var response = await httpClient.GetAsync(queryString);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
var model = Newtonsoft.Json.JsonConvert.DeserializeObject<MeuModelo>(json)
return Json(model);
}
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, "Erro ao acessar a API.");
}
}
EDIT
The AP has asked to list some other approaches, so let’s go.:
HttpWebRequest
- Quite complex, but allows you to control every aspect of the request.
WebClient
- Abstraction of HttpWebRequest
, quite simple, without many controls.
HttpClient
- Available on .NET 4.5
, allows operation async/await
and combines the best of HttpWebRequest
and WebClient
.
RestSharp
- Similar to the HttpClient
, but without the async/await
and with better compatibility.
So, in your case, the HttpClient
is the most appropriate.
You want to know what, specifically? How to request this API using C#?
– Jéf Bueno
@LINQ exactly that.. Thank you
– Thomas Erich Pimentel
Thomas, it still gets a little wide. Do you want to do it all "in hand"? Use some third party library?
– Jéf Bueno
@LINQ, so today I’m using
Entity Framework
,Jquery
but I don’t know what the best approach would be.. I saw the staff usingAjax
to consume the data, the data coming from this API will be updated frequently.. virtually every page update, I will need to retrieve the data again..– Thomas Erich Pimentel