【问题标题】:Can I get data from web api in .net core with another api or api key?我可以使用另一个 api 或 api 密钥从 .net 核心中的 web api 获取数据吗?
【发布时间】:2021-10-31 21:15:45
【问题描述】:

我写了一个控制器。我根据我将在此处使用的 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);
    }
}

【问题讨论】:

  • 这不是您问题的答案,但我建议read more about using HttpClient。对于这个问题,你能提供更多细节吗?你想要达到的目标还不够清楚。
  • 我想使用我创建的 API 从外部 Web API 中提取数据。我不知道从哪里开始。

标签: asp.net-core asp.net-core-mvc asp.net-core-webapi


【解决方案1】:

基本上你需要这些步骤:

  • HttpClient 用于本地 API。
  • HttpClient 用于外部 API。
  • 本地 API 控制器。
  • 将外部客户端注入本地 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
    }
}

用于外部 API 的 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 发出 webrequest 请求。我在这个方法中添加了 HttpGet 注释。
  • 很高兴知道您找到了解决方案。
猜你喜欢
  • 1970-01-01
  • 2023-02-05
  • 2019-04-18
  • 1970-01-01
  • 2019-10-25
  • 2020-05-28
  • 1970-01-01
  • 2018-01-29
  • 2020-05-31
相关资源
最近更新 更多