使用www.example.com核心API从外部API获取数据asp.net

lpwwtiir  于 2023-05-19  发布在  .NET
关注(0)|答案(1)|浏览(132)

我正在学习使用ASP.NET核心创建API,在此我遇到了一个问题,我试图使用我的API执行一个外部API的请求,但我不知道如何执行请求并返回请求的JSON,有帮助吗?
应用程序的流程如下所示:

SPA -> AspNet Core WEB API ->外部API

到目前为止我所做的:

[Route("api/[Controller]")]
    public class RankingsController : Controller
    {
        private readonly IRankingRepository _rankingRepository;

        public RankingsController(IRankingRepository rankingRepo)
        {
            _rankingRepository = rankingRepo;
        }

        [HttpGet("{id}", Name = "GetRanking")]
        public IActionResult GetById(long id)
        //Here is where I want to make the requisition
        }

    }

我需要请求这个API:
http://api.football-data.org/v1/competitions/ {id}/leagueTable

  • 在ID位置,我需要传递一个参数,该参数来自我的API中发出的请求;*

对这个问题有什么帮助吗?
抱歉,这不是一个复杂的问题。
谢谢!

yqlxgs2m

yqlxgs2m1#

您可以使用HttpClient示例来实现您想要的功能。但是,我总是发现使用RestSharp更容易。
当然,这取决于你的约束条件,但假设你在这种情况下没有约束条件,你可以使用RestSharp来调用外部API:

安装:

Install-Package RestSharp

用法:

using RestSharp;

[HttpGet("{id}", Name = "GetRanking")]
public async Task<IActionResult> GetByIdAync(long id)
{
    var client = new RestClient($"http://api.football-data.org/v1/competitions/{id}/leagueTable");
    var request = new RestRequest(Method.GET);
    IRestResponse response = await client.ExecuteAsync(request);

    //TODO: transform the response here to suit your needs
   
    return Ok(data);
}

要使用RestSharp的rest响应,必须使用response.Content属性。
例如,您可以将其反序列化为Json,对其进行操作以满足您的需求,并将所需的数据返回给API调用者。

示例:

假设我想获得英超联赛2017/18的排名(Id = 445):

  • 下面我将从传说中的Newtonsoft.Json包和一点jpath语法中获得很多帮助,但我假设你已经使用了这两种语法 *:)
    创建一对模型来保存要返回给API调用者的值:
public class LeagueTableModel
{
    public string LeagueCaption { get; set; }

    public IEnumerable<StandingModel> Standings { get; set; }
}
public class StandingModel
{
    public string TeamName { get; set; }

    public int Position { get; set; }
}

在服务类中实现下面的方法,通过DI/IoC注入到控制器中,以避免耦合并增加可测试性(我们都知道我们应该这样做,对吗?)。我假设这个类在您的示例中是RankingRepository

public RankingRepository: IRankingRepository 
{
    public Task<LeagueTableModel> GetRankingsAsync(long id)
    {
        var client = new RestClient($"http://api.football-data.org/v1/competitions/{id}/leagueTable");
        var request = new RestRequest(Method.GET);
        IRestResponse response = await client.ExecuteAsync(request);
        if (response.IsSuccessful)
        {
            var content = JsonConvert.DeserializeObject<JToken>(response.Content);
    
            //Get the league caption
            var leagueCaption = content["leagueCaption"].Value<string>();
    
            //Get the standings for the league.
            var rankings = content.SelectTokens("standing[*]")
                .Select(team => new StandingModel
                {
                    TeamName = (string)team["teamName"],
                    Position = (int)team["position"]
                })
                .ToList();
    
            //return the model to my caller.
            return new LeagueTableModel
            {
                LeagueCaption = leagueCaption,
                Standings = rankings
            };
        }
    
        //TODO: log error, throw exception or do other stuffs for failed requests here.
        Console.WriteLine(response.Content);
    
        return null;
    }
}

从控制器使用:

[Route("api/[Controller]")]
public class RankingsController : Controller
{
    private readonly IRankingRepository _rankingRepository;

    public RankingsController(IRankingRepository rankingRepo)
    {
        _rankingRepository = rankingRepo;
    }

    [HttpGet("{id}", Name = "GetRanking")]
    public Task<IActionResult> GetByIdAsync(long id)
        //Here is where I want to make the requisition
        var model = await _rankingRepository.GetRankingsAsync(id);
        
        //Validate if null
        if (model == null)
            return NotFound(); //or any other error code accordingly. Bad request is a strong candidate also.

        return Ok(model);
    }
}

希望这有帮助!

相关问题