2

I wrote a controller. I wrote it according to the web api I will use here. But how should I make my own created api? Do I need to have my own created api where I write with HttpPost? I might be wrong as I am new to this.

public class GoldPriceDetailController : Controller
{
    string Baseurl = "https://apigw.bank.com.tr:8003/";
    public async Task<ActionResult> GetGoldPrice()
    {
        List<GoldPrice> goldPriceList = new List<GoldPrice>();
        using (var client = new HttpClient())
        {
            //Passing service base url  
            client.BaseAddress = new Uri(Baseurl);
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //Sending request to find web api REST service resource GetDepartments using HttpClient  
            HttpResponseMessage Res = await client.GetAsync("getGoldPrices");
            Console.WriteLine(Res.Content);

            //Checking the response is successful or not which is sent using HttpClient  
            if (Res.IsSuccessStatusCode)
            {
                var ObjResponse = Res.Content.ReadAsStringAsync().Result;
                goldPriceList = JsonConvert.DeserializeObject<List<GoldPrice>>(ObjResponse);
            }

            //returning the student list to view  
            return View(goldPriceList);
        }
    } 
    
     [HttpPost]
     public async Task<IActionResult> GetReservation(int id)
     {
         GoldPrice reservation = new GoldPrice();
         using (var httpClient = new HttpClient())
         {
             using (var response = await httpClient.GetAsync("https://apigw.bank.com.tr:8443/getGoldPrices" + id))
             {
                 if (response.StatusCode == System.Net.HttpStatusCode.OK)
                 {
                     string apiResponse = await response.Content.ReadAsStringAsync();
                     reservation = JsonConvert.DeserializeObject<GoldPrice>(apiResponse);
                 }
                 else
                     ViewBag.StatusCode = response.StatusCode;
             }
         }

         return View(reservation);
    }
}
Aysenur
  • 29
  • 1
  • 4
  • This is not an answer to your question, but I recommend to [read more about using `HttpClient`](https://stackoverflow.com/a/65445988/5519026). And for the question, can you provide more details? it is not clear enough what you want to achieve. – LazZiya Sep 02 '21 at 13:40
  • 1
    I want to pull data from an external web API with the API I created. I didn't know where to start. – Aysenur Sep 02 '21 at 14:14

1 Answers1

2

Basically you need these steps:

  • HttpClient for local API.
  • HttpClient for external API.
  • Local API controller.
  • Inject external client into the local API.
  • Then inject the local API client into the razor page/controller.

HttpClient for Local API

public class LocalApiClient : ILocalHttpClient
{
    private readonly HttpClient _client;

    public LocalAPiClient(HttpClient client)
    {
        _client = client;
        _client.BaseAddress(new Uri("https://localapi.com"));
    }

    [HttpGet]
    public async Task<string> GetGoldPrices(int id)
    {
        // logic to get prices from local api
        var response = await _client.GetAsync($"GetGoldPrices?id={id}");

        // deserialize or other logic
    }
}

HttpClient for External API

public class ExternalApiClient : IExternalHttpClient
{
    private readonly HttpClient _client;

    public ExternalAPiClient(HttpClient client)
    {
        _client = client;
        _client.BaseAddress(new Uri("https://externalApi.com"));

        // ...

    }

    [HttpGet]
    public async Task<string> GetGoldPrices(int id)
    {
        // logic to get prices from external api
        var response = await _client.GetAsync("getGoldPrices?id=" + id))

    }
}

Register your clients in startup

services.AddHttpClient<ILocalHttpClient, LocalHttpClient>();
services.AddHttpClient<IExternalHttpClient, ExternalHttpClient>();

Create Local API Controller

and inject the external http client into it

[ApiController]
public class LocalAPIController : Controller
{
    private readonly IExternalHttpClient _externalClient;

    public LocalAPIController(IExternalHttpClient externalClient)
    {
        _externalClient = externalClient;
    }

    [HttpGet]
    public async Task<string> GetGoldPrices(int id)
    {
        var resoponse = await _externalClient.GetGoldPrices(id);
        // ...
    }
}

Inject the local client into razor page/controller

public class HomeController : Controller
{
    private readonly ILocalHttpClient _localClient;

    public HomeController(ILocalHttpClient localClient)
    {
        _localClient = localClient;
    }

    public async Task<IActionResult> Index(int id)
    {
        var response = await _localClient.GetGoldPrices(id);
        // ...
    }
}
LazZiya
  • 5,286
  • 2
  • 24
  • 37
  • 1
    Thank you for your answer. I didn't explain my problem properly. But I finally got what I wanted. I created a method and made a webrequest request to the external api. I added HttpGet annotation to this method. – Aysenur Sep 06 '21 at 21:46
  • Glad to know that you found a solution. – LazZiya Sep 07 '21 at 06:58
  • Where are `ILocalHttpClient` and `IExternalHttpClient` defined? If these are custom interfaces, providing the basic implementation here will make it more useful to others. – Tawab Wakil May 10 '22 at 20:37
  • 1
    @TawabWakil, they are custom interfaces nothing special and actually you don't have to implement the interfaces, I used them just for convention, you can register the services just like `services.AddHttpClient();` – LazZiya May 11 '22 at 04:51