Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Blazor - prerendering
@page
@using BlazorPreRendering.Client
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>BlazorPreRendering</title>
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<link href="BlazorPreRendering.Client.styles.css" rel="stylesheet" />
</head>
<body>
<component type="typeof(App)" render-mode="WebAssemblyPrerendered" />
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
@using BlazorPreRendering.Server
@namespace BlazorPreRendering.Server.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@page "/fetchdata"
@using BlazorPreRendering.Shared
@using BlazorPreRendering.Shared.Services
@inject IWeatherForecastService Service
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>
@if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}
@code {
private WeatherForecast[] forecasts;
protected override async Task OnInitializedAsync()
{
forecasts = await Service.GetForecastAsync();
}
}
@page "/fetchdata"
@using BlazorPreRendering.Shared
@using BlazorPreRendering.Shared.Services
@inject IWeatherForecastService Service
@inject IPreRenderService PreRenderService
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>
@if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}
@code {
private WeatherForecast[] forecasts;
protected override async Task OnInitializedAsync()
{
if (PreRenderService.IsPreRendering == false)
{
forecasts = await Service.GetForecastAsync();
}
}
}
public interface IWeatherForecastService
{
Task<WeatherForecast[]> GetForecastAsync();
}
public class PreRenderService : IPreRenderService
{
public bool IsPreRendering { get; private set; }
public PreRenderService()
{
}
public PreRenderService(IHttpContextAccessor httpContextAccessor)
{
if (httpContextAccessor.HttpContext.Response.HasStarted)
{
IsPreRendering = false;
}
else
{
IsPreRendering = true;
}
}
}
public interface IPreRenderService
{
bool IsPreRendering { get; }
}
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
//builder.RootComponents.Add<App>("#app");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
await builder.Build().RunAsync();
}
}
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
//builder.RootComponents.Add<App>("#app");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped<IWeatherForecastService, WeatherForecastService>();
await builder.Build().RunAsync();
}
}
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
//builder.RootComponents.Add<App>("#app");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped<IWeatherForecastService, WeatherForecastService>();
builder.Services.AddScoped<IPreRenderService, PreRenderService>();
await builder.Build().RunAsync();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddRazorPages();
services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://localhost:44363/") });
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddRazorPages();
services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://localhost:44363/") });
services.AddScoped<IWeatherForecastService, WeatherForecastService>();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddRazorPages();
services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://localhost:44363/") });
services.AddScoped<IWeatherForecastService, WeatherForecastService>();
services.AddHttpContextAccessor();
services.AddScoped<IPreRenderService, PreRenderService>();
}
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
//endpoints.MapFallbackToFile("index.html");
endpoints.MapFallbackToPage("/_Host");
});
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;
private readonly IWeatherForecastService _weatherForecastService;
public WeatherForecastController(ILogger<WeatherForecastController> logger,
IWeatherForecastService weatherForecastService)
{
_logger = logger;
_weatherForecastService = weatherForecastService;
}
[HttpGet]
public async Task<IEnumerable<WeatherForecast>> Get()
{
return await _weatherForecastService.GetForecastAsync();
}
}
public class WeatherForecastService : IWeatherForecastService
{
private readonly HttpClient _httpClient;
public WeatherForecastService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<WeatherForecast[]> GetForecastAsync()
{
return await _httpClient.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
}
}
public class WeatherForecastService : IWeatherForecastService
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
public async Task<WeatherForecast[]> GetForecastAsync()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.