使用HttpClient调用WeatherAPI

时间:2018-09-28 04:33:08

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

我创建了Web API,以接收来自OpenWeatherAPI的每日温度。 我将API调用放在MVC项目中; (计划稍后创建新项目,以改善微服务架构。)

有人在代码中提到:

  

在您的HomeController中,您尝试只是像在WeatherController实例上的方法一样调用操作。您还需要在那里使用HttpClient。另外,不要直接新建HttpClient。应该将其视为单例

我该如何进行?这是一个月前开始编程的原始代码。

MVC页面:

namespace WeatherPage.Controllers
{
    public class HomeController : Controller
    {

        public WeatherController weathercontroller = new WeatherController();

        public IActionResult Index()
        {
            return View();
        }

        public Async Task<IActionResult> About()
        {
            ViewData["Message"] = "Your application description page.";
            ViewData["test"] =  weathercontroller.City("Seattle");
            return View();
        }
    }
}

API控制器:

[Route("api/[controller]")] 
public class WeatherController : ControllerBase
{
    [HttpGet("[action]/{city}")]
    public async Task<IActionResult> City(string city)
    {
        Rootobject rawWeather = new Rootobject();
        using (var client = new HttpClient())
        {
            try
            {
                client.BaseAddress = new Uri("http://api.openweathermap.org");
                var response = await client.GetAsync($"/data/2.5/weather?q={city}&appid=APIkey&units=metric");
                response.EnsureSuccessStatusCode();

                var stringResult = await response.Content.ReadAsStringAsync();
                rawWeather = JsonConvert.DeserializeObject<Rootobject>(stringResult);
                return Ok(rawWeather);
            }
            catch (HttpRequestException httpRequestException)
            {
                return BadRequest($"Error getting weather from OpenWeather: {httpRequestException.Message}");
            }
        }
    }
}   

public class Rootobject
{
    public Coord coord { get; set; }
    public Weather[] weather { get; set; }
    public string _base { get; set; }
    public Main main { get; set; }
    public int visibility { get; set; }
    public Wind wind { get; set; }
    public Clouds clouds { get; set; }
    public int dt { get; set; }
    public Sys sys { get; set; }
    public int id { get; set; }
    public string name { get; set; }
    public int cod { get; set; }
}

这适用于我的项目: https://localhost:55555/api/weather/city/washington

Retrieve Data From Third party Openweather Api

Should We Call Web Api from Mvc Application in Same Solution

1 个答案:

答案 0 :(得分:2)

这大致意味着您应该使用依赖项注入。

  1. 不要在需要时每次都创建HttpClient实例,而只需请求HttpClient实例即可。
  2. 将您在天气控制器中获取天气的代码提取到服务中,并在天气控制器api和家庭控制器中同时请求该服务

WeatherService

public interface IWeatherService
{
    Task<Rootobject> CityAsync(string city);
}

public class WeatherService : IWeatherService{
    private HttpClient _httpClient ;
    public WeatherService(IHttpClientFactory clientFactory){
        this._httpClient = clientFactory.CreateClient();
    }


    public async Task<Rootobject> CityAsync(string city){
        Rootobject rawWeather = new Rootobject();
        this._httpClient.BaseAddress = new Uri("http://api.openweathermap.org");
        var response = await this._httpClient.GetAsync($"/data/2.5/weather?q={city}&appid=APIkey&units=metric");
        response.EnsureSuccessStatusCode();

        var stringResult = await response.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<Rootobject>(stringResult);
    }

}

新的WeatherController:

[Route("api/[controller]")] 
public class WeatherController : ControllerBase
{
    private IWeatherService _weatherService;

    public WeatherController(IWeatherService wetherService ){
        this._weatherService= wetherService;
    }

    [HttpGet("[action]/{city}")]
    public async Task<IActionResult> City(string city)
    {
        try
        {
            var rawWeather=await this._weatherService.CityAsync(city);
            return Ok(rawWeather);
        }
        catch (HttpRequestException httpRequestException)
        {
            return BadRequest($"Error getting weather from OpenWeather: {httpRequestException.Message}");
        }
    }
}

新的HomeController:

public class HomeController : Controller
{
    private IWeatherService _weatherService;
    public HomeController(IWeatherService wetherService ){
        this._weatherService= wetherService;
    }

    public IActionResult Index()
    {
        return View();
    }

    public async Task<IActionResult> About()
    {
        ViewData["Message"] = "Your application description page.";
        ViewData["test"] =  await this._weatherService.CityAsync("Seattle");

        return View();
    }

}

ConfigureServices:

services.AddHttpClient();
services.AddSingleton<IWeatherService ,WeatherService>();