From df000698fda92cc887e7644b0715ad8ea9689a00 Mon Sep 17 00:00:00 2001 From: Jon Galloway Date: Thu, 20 Feb 2025 17:00:05 -0800 Subject: [PATCH] Improve zones.json for deployment Fixes #43 Embed `zones.json` as a resource and modify code to read it. * **Api.csproj** - Add `zones.json` as an embedded resource. * **NwsManager.cs** - Modify `GetZonesAsync` method to read `zones.json` as an embedded resource instead of from the `wwwroot` folder. - Remove the `webHostEnvironment` parameter from the `NwsManager` constructor. --- For more details, open the [Copilot Workspace session](https://copilot-workspace.githubnext.com/dotnet-presentations/dotnet-aspire-workshop/issues/43?shareId=XXXX-XXXX-XXXX-XXXX). --- complete/Api/Api.csproj | 5 ++++- complete/Api/Data/NwsManager.cs | 16 +++++++++------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/complete/Api/Api.csproj b/complete/Api/Api.csproj index b727a16..6b0a352 100644 --- a/complete/Api/Api.csproj +++ b/complete/Api/Api.csproj @@ -12,4 +12,7 @@ - \ No newline at end of file + + + + diff --git a/complete/Api/Data/NwsManager.cs b/complete/Api/Data/NwsManager.cs index e6fdc1c..6482843 100644 --- a/complete/Api/Data/NwsManager.cs +++ b/complete/Api/Data/NwsManager.cs @@ -1,12 +1,13 @@ using System.Text.Json; using System.Web; +using System.Reflection; using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.Extensions.Caching.Memory; using Api.Data; namespace Api { - public class NwsManager(HttpClient httpClient, IMemoryCache cache, IWebHostEnvironment webHostEnvironment) + public class NwsManager(HttpClient httpClient, IMemoryCache cache) { private static readonly JsonSerializerOptions options = new(JsonSerializerDefaults.Web); @@ -25,15 +26,16 @@ public class NwsManager(HttpClient httpClient, IMemoryCache cache, IWebHostEnvir // .Distinct() // .ToArray() ?? []; - // Deserialize the zones.json file from the wwwroot folder - var zonesFilePath = Path.Combine(webHostEnvironment.WebRootPath, "zones.json"); - if (!File.Exists(zonesFilePath)) + // Deserialize the zones.json file from the embedded resource + var assembly = Assembly.GetExecutingAssembly(); + var resourceName = "Api.wwwroot.zones.json"; + using var stream = assembly.GetManifestResourceStream(resourceName); + if (stream == null) { return []; } - using var zonesJson = File.OpenRead(zonesFilePath); - var zones = await JsonSerializer.DeserializeAsync(zonesJson, options); + var zones = await JsonSerializer.DeserializeAsync(stream, options); return zones?.Features ?.Where(f => f.Properties?.ObservationStations?.Count > 0) @@ -122,4 +124,4 @@ public static IServiceCollection AddNwsManager(this IServiceCollection services) return app; } } -} \ No newline at end of file +}