Hello, there are some approaches, I'll cite the one I think is more appropriate, which is using HttpClient
.
If you can 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 asked to list some other approaches, so come on.
-
HttpWebRequest
- Quite complex, but allows you to control every aspect of the request.
-
WebClient
- Abstraction of HttpWebRequest
, quite simple, without many controls.
-
HttpClient
- Available in .NET 4.5
, allows operation async/await
and combines best of HttpWebRequest
and WebClient
.
-
RestSharp
- Similar to HttpClient
, but with async/await
and better compatibility.
Then, in your case, HttpClient
is the most indicated.