|
| 1 | +using FrontEndBackEndDemo.Web.Models; |
| 2 | +using FrontEndBackEndDemo.Web.Options; |
| 3 | +using Microsoft.AspNetCore.Mvc; |
| 4 | +using Microsoft.Extensions.Options; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Diagnostics; |
| 7 | +using System.IO; |
| 8 | +using System.Net.Http; |
| 9 | +using System.Text.Json; |
| 10 | +using System.Threading.Tasks; |
| 11 | + |
| 12 | +namespace FrontEndBackEndDemo.Web.Controllers |
| 13 | +{ |
| 14 | + public class HomeController : Controller |
| 15 | + { |
| 16 | + private readonly IHttpClientFactory _httpClientFactory; |
| 17 | + private readonly IOptionsMonitor<BackEndOptions> _backEndOptionOptionsAccessor; |
| 18 | + |
| 19 | + public HomeController( |
| 20 | + IHttpClientFactory httpClientFactory, |
| 21 | + IOptionsMonitor<BackEndOptions> backEndOptionOptionsAccessor) |
| 22 | + { |
| 23 | + _httpClientFactory = httpClientFactory; |
| 24 | + _backEndOptionOptionsAccessor = backEndOptionOptionsAccessor; |
| 25 | + } |
| 26 | + |
| 27 | + public async Task<IActionResult> Index() |
| 28 | + { |
| 29 | + HttpClient httpClient = _httpClientFactory.CreateClient(); |
| 30 | + HttpResponseMessage backEndApiResponseMessage = await httpClient.GetAsync( |
| 31 | + _backEndOptionOptionsAccessor.CurrentValue.BackEndApiEndPoint); |
| 32 | + if (backEndApiResponseMessage.IsSuccessStatusCode) |
| 33 | + { |
| 34 | + using Stream backEndApiResponseStream = |
| 35 | + await backEndApiResponseMessage.Content.ReadAsStreamAsync(); |
| 36 | + IEnumerable<WeatherForecast>? weatherForecast = |
| 37 | + await JsonSerializer.DeserializeAsync<IEnumerable<WeatherForecast>>(backEndApiResponseStream); |
| 38 | + return View(weatherForecast); |
| 39 | + } |
| 40 | + return NotFound(); |
| 41 | + } |
| 42 | + |
| 43 | + public IActionResult Privacy() |
| 44 | + { |
| 45 | + return View(); |
| 46 | + } |
| 47 | + |
| 48 | + [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] |
| 49 | + public IActionResult Error() |
| 50 | + { |
| 51 | + return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments