Last active
October 12, 2023 17:02
-
-
Save richlander/3b41d7496f2d8533b2d88896bd31e764 to your computer and use it in GitHub Desktop.
Get Weather Forecast -- with records
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Net.Http; | |
using System.Net.Http.Json; | |
string serviceURL = "https://localhost:5001/WeatherForecast"; | |
HttpClient client = new(); | |
Forecast[] forecasts = await client.GetFromJsonAsync<Forecast[]>(serviceURL); | |
foreach(Forecast forecast in forecasts) | |
{ | |
Console.WriteLine($"{forecast.Date}; {forecast.TemperatureC}C; {forecast.Summary}"); | |
} | |
// {"date":"2020-09-06T11:31:01.923395-07:00","temperatureC":-1,"temperatureF":31,"summary":"Scorching"} | |
public record Forecast(DateTime Date, int TemperatureC, int TemperatureF, string Summary); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Project Sdk="Microsoft.NET.Sdk"> | |
<PropertyGroup> | |
<OutputType>Exe</OutputType> | |
<TargetFramework>net5.0</TargetFramework> | |
<LangVersion>preview</LangVersion> | |
</PropertyGroup> | |
</Project> |
All we need now is dotnet run script <path-to-.cs-file>
which uses a default .csproj
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The JSON required by this code is provided by the .NET SDK webapi template. You run the web service app created by the template, which will generate weather forecast (as JSON).
You can try this on your own machine, with the following .NET SDK commands. It requires .NET 5.0 Preview 8 or later.
Make sure you've run
dotnet dev-certs https --trust
first or the handshake between client and server won't work.That will start the webserver, which will expose the forecast service at the following URL by default:
https://localhost:5001/WeatherForecast
. You can then run the sample above.