我可以使用另一个API或API密钥从.Net核心中的Web API获取数据吗? [英] Can I get data from web api in .net core with another api or api key?

查看:21
本文介绍了我可以使用另一个API或API密钥从.Net核心中的Web API获取数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个控制器。我是根据我将在这里使用的web API编写的。但是我应该如何制作我自己创建的API呢? 我是否需要在用HttpPost编写的地方拥有自己创建的API?我可能错了,因为我是新手。

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);
    }
}

推荐答案

基本上需要以下步骤:

  • HttpClient用于本地接口
  • HttpClient用于外部接口
  • 本地API控制器。
  • 将外部客户端注入本地API
  • 然后将本地API客户端注入到剃须刀页面/控制器中。

HttpClient本地接口

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

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))

    }
}

startup中注册您的客户端

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

创建本地API控制器

并将外部http客户端注入其中

[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);
        // ...
    }
}

将本地客户端注入剃须刀页面/控制器

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);
        // ...
    }
}

这篇关于我可以使用另一个API或API密钥从.Net核心中的Web API获取数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆