Search code examples
visual-studiodotnet-httpclientblazor-webassembly

In the default Visual Studio Blazor WebAssembly app, how would you move the WeatherForecast class into a separate project?


If I could figure this out, I could redo my Blazor Server app as a WebAssembly app.

Out of the box, the WebAssembly Solution appears as follows with the WeatherForecast class in FetchData.razor.:
Starting Solution


I want to refactor this so that the WeatherForecast class is moved from FetchData.razor to WeatherForecast.cs in a separate C# Class Library project.

Target Solution

What changes to which bits are needed to achieve this?


Solution

  • The weather forecast class, in a separate class library, looks like this:

    using System.Net.Http.Json;
    namespace WeatherForecastNamespace
    {
        public class WeatherForecast
        {
            public DateTime Date { get; set; }
            public int TemperatureC { get; set; }
            public string? Summary { get; set; }
            public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
            public static async Task<WeatherForecast[]?> GetWeatherForecasts(HttpClient Http)
            {
                return await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
            }
        }
    }
    

    And the FetchData.razor @code block, with the old code commented out, looks like this:

    @code {
        private WeatherForecast[]? forecasts;
    
        protected override async Task OnInitializedAsync()
        {
            //forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
            forecasts = await WeatherForecast.GetWeatherForecasts(Http);
        }
    
        //public class WeatherForecast
        //{
        //    public DateTime Date { get; set; }
    
        //    public int TemperatureC { get; set; }
    
        //    public string? Summary { get; set; }
    
        //    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
        //}
    }
    

    If there are problems with this approach, I'd appreciate hearing about them.