Created
October 3, 2024 16:06
-
-
Save amantix/b4aa1083e0efb853e3311c4deb43d5a8 to your computer and use it in GitHub Desktop.
Simple web api using HttpListener
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.Net; | |
using System.Text.Json; | |
namespace HttpListenerApplication; | |
class Program | |
{ | |
private record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary) | |
{ | |
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); | |
} | |
static async Task Main(string[] args) | |
{ | |
var listener = new HttpListener(); | |
listener.Prefixes.Add("http://localhost:5032/"); | |
string[] summaries = | |
[ | |
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" | |
]; | |
listener.Start(); | |
while (listener.IsListening) | |
{ | |
var context = await listener.GetContextAsync(); | |
Task.Run(async () => | |
{ | |
if (context.Request.HttpMethod == "GET" && context.Request.RawUrl == "/weatherforecast/") | |
{ | |
context.Response.ContentType = "application/json"; | |
context.Response.StatusCode = 200; | |
var forecast = Enumerable.Range(1, 5).Select(index => | |
new WeatherForecast | |
( | |
DateOnly.FromDateTime(DateTime.Now.AddDays(index)), | |
Random.Shared.Next(-20, 55), | |
summaries[Random.Shared.Next(summaries.Length)] | |
)) | |
.ToArray(); | |
var buffer = JsonSerializer.SerializeToUtf8Bytes(forecast); | |
context.Response.ContentLength64 = buffer.Length; | |
await context.Response.OutputStream.WriteAsync(buffer, 0, buffer.Length); | |
} | |
else | |
{ | |
context.Response.StatusCode = 404; | |
} | |
context.Response.Close(); | |
} | |
); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment