· 4 years ago · Apr 24, 2021, 08:44 PM
1using System;
2using System.Net.Http;
3using System.Threading.Tasks;
4using Microsoft.AspNetCore.Mvc.RazorPages;
5using System.IO;
6using Newtonsoft.Json.Linq;
7
8namespace WeatherApp.Pages
9{
10 public class IndexModel : PageModel
11 {
12 // URL where i call the API
13 private string _url = "http://api.weatherapi.com/v1/current.json?key=";
14 //Information class about the weather
15 public Information Info { get; private init; }
16 //Location class about the weather
17 public Location Location { get; private set; }
18
19 //String where's the response JSON sent by API
20 private string _result = "";
21
22 public IndexModel()
23 {
24 Info = new Information();
25 string key;
26
27 /*
28 * Take the API key:
29 * - If there's the file (localhost) it take the key from the file
30 * - If there isn't the file (Server) it the the key from Environment variable
31 */
32 try
33 {
34 var read = new StreamReader("API.txt");
35 key = read.ReadLine();
36 }
37 catch (Exception)
38 {
39 key = Environment.GetEnvironmentVariable("ApiKey");
40 }
41
42 _url += key;
43 }
44
45 public async Task OnPostSearch(string city)
46 {
47 //Call the API and take the JSON
48 using (var req = new HttpClient())
49 {
50 _url += $"&q={city}&aqi=no";
51 try
52 {
53 _result = await req.GetStringAsync(_url);
54 }
55 catch (HttpRequestException)
56 {
57 Info.Text = "Please insert a valid city";
58 return;
59 }
60 catch (Exception)
61 {
62 Info.Text = "Error!";
63 return;
64 }
65 }
66
67 //Deserializing JSON and taking the information that are stored in the class
68 var deserialized = JObject.Parse(_result);
69 try
70 {
71 Info.TempC = deserialized["current"]?["temp_c"]?.ToObject<double>();
72 Info.Text = deserialized["current"]?["condition"]?["text"]?.ToString();
73 Info.Icon = deserialized["current"]?["condition"]?["icon"]?.ToString();
74 Location = deserialized["location"]?.ToObject<Location>();
75 }
76 catch (NullReferenceException)
77 {
78 RedirectToPage("Index");
79 }
80 catch (InvalidOperationException)
81 {
82 RedirectToPage("Index");
83 }
84 }
85 }
86
87 //Class information where there's the weather information
88 public class Information
89 {
90 public string Text { get; set; }
91 public string Icon { get; set; }
92 public double? TempC { get; set; }
93 }
94
95 //Class location where there's the location chosen by the user
96 public class Location
97 {
98 public Location(string name, string region, string country)
99 {
100 Name = name;
101 Region = region;
102 Country = country;
103 }
104
105 private string Name { get; set; }
106 private string Region { get; set; }
107 private string Country { get; set; }
108
109 public override string ToString()
110 {
111 return $"{Name}, {Region}, {Country}";
112 }
113 }
114}