Skip to content

Instantly share code, notes, and snippets.

@richlander

richlander/Program.cs

Last active Dec 7, 2020
Embed
What would you like to do?
Get Weather Forecast -- with records
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);
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>preview</LangVersion>
</PropertyGroup>
</Project>
@richlander

This comment has been minimized.

Copy link
Owner Author

@richlander richlander commented Sep 8, 2020

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.

rich@thundera ~ % dotnet new webapi -o webapi
rich@thundera ~ % cd webapi 
rich@thundera webapi % dotnet run

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.

rich@thundera ~ % git clone https://gist.github.com/3b41d7496f2d8533b2d88896bd31e764.git weather-forecast
rich@thundera ~ % cd weather-forecast
rich@thundera weather-forecast % dotnet run
9/9/2020 12:09:19 PM; 24C; Chilly
9/10/2020 12:09:19 PM; 54C; Mild
9/11/2020 12:09:19 PM; -2C; Hot
9/12/2020 12:09:19 PM; 24C; Cool
9/13/2020 12:09:19 PM; 45C; Balmy
@mrsauravsahu

This comment has been minimized.

Copy link

@mrsauravsahu mrsauravsahu commented Oct 30, 2020

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