How do I save and load data within a component in Blazor?

By utilizing browser storage in Blazor, you can effectively save and load data within a component. In the following example, you can see how the counter value is updated with a button click and the count value is stored in the local storage of the browser. When you refresh the page, the saved data will be loaded from the browser’s local storage. [Index.razor] Refer to this link for more details.

On Trying to Debug an application, by the F5 key I get the error: ‘Error while trying to run project: Unable to start debugging on the web server. Catastrophic failure’

This issue occurs if the account that is used to run the ASP.NET Worker process (by default, the ASPNET user account) is not assigned the ‘Impersonate a client after authentication’ user right in the ‘Local Security Policy’ settings. This issue may occur when you install Microsoft Visual Studio .NET after you install Windows 2000 Service Pack 4 (SP4) on the computer. In this situation, the ASPNET account is not assigned the ‘Impersonate a client after authentication’ user right in the ‘Local Security Policy’ settings.To resolve it, please use the method at: To work around the problem, manually assign Impersonate a client after authentication to the IWAM account. To do so, follow these steps: Click Start, point to Programs, point to Administrative Tools, and then click Domain Controller Security Policy. Click Security Settings. Click Local Policies, and then click User Rights Assignment. In the right pane, double-click Impersonate a client after authentication. In the Security Policy Setting window, click Define these policy settings. Click Add, and then click Browse. In the Select Users or Groups window, select the IWAM account name, click Add, and then click OK. Click OK, and then click OK again. To enforce an update of computer policy, type the following command: secedit /refreshpolicy machine_policy /enforce At a command prompt, type iisreset.In case your server is a Domain Controller Refer PRB: ‘Catastrophic Failure’ Error Message When You Try to Debug an ASP.NET Application on Windows 2000 Domain Controller

How do I use IndexedDB in Blazor WebAssembly?

IndexedDB is used for the client-side storage of data and files. Follow these steps to use IndexedDB in Blazor WebAssembly: Create a Blazor WebAssembly app and install the IndexedDB.Blazor NuGet package using the NuGet package manager. Set up the IIndexedDbFactory configuration service in your Program.cs file and set it as scoped.[Program.cs] using IndexedDB.Blazor;builder.Services.AddScoped(); Now add the properties inside the class to store and process data in the Data folder.[IndexDb.cs] using IndexedDB.Blazor; using Microsoft.JSInterop; using System.ComponentModel.DataAnnotations;namespace Blazor_WebAssembly_App.Data { public class IndexDb : IndexedDb { public IndexDb ( IJSRuntime jSRuntime, string name, int version ) : base(jSRuntime, name, version) { } // These are like tables. Declare as many of them as you want. public IndexedSet employee { get; set; } } public class Employee { [Key] public int Id { get; set; } [Required] public string? FirstName { get; set; } [Required] public string? LastName { get; set; } }} Add the namespace for the IndexedDB in _Import.razor file.[_Import.razor] @using IndexedDB.Blazor @using {{Your_App_Name}}.Data Add the Razor component to add and store the data using IndexedDB in the Index.razor file.[_Import.razor] @page “/” @inject IIndexedDbFactory DbFactory <h1>employee</h1> @if (employee != null){ <table class=”table”> <thead> <tr> <th>ID</th> <th>First name</th> <th>Last name</th> <th></th> </tr> </thead> <tbody> @foreach (var Employee in employee) { <tr> <td>@Employee.Id</td> <td>@Employee.FirstName</td> <td>@Employee.LastName</td> <td> <button class=”btn btn-danger” @onclick=”() => DeleteEmployee(Employee.Id)”>Delete</button> </td> </tr> } </tbody> </table>}<fieldset> <legend>Add new Employee</legend> <EditForm Model=”@newEmployee” OnValidSubmit=”@SaveNewEmployee”> <InputText @bind-Value=”@newEmployee.FirstName” placeholder=”First name…” /> <InputText @bind-Value=”@newEmployee.LastName” placeholder=”Last name…” /> <button type=”submit”>Add</button> <p><ValidationSummary /></p> <DataAnnotationsValidator /> </EditForm></fieldset>@code { List<Employee>? employee; protected override async Task OnInitializedAsync () { await RefreshEmployeeList(); } Employee newEmployee = new Employee(); async Task RefreshEmployeeList () { using var db = await DbFactory.Create<IndexDb>(); employee = db.employee.ToList(); } async Task SaveNewEmployee () { using var db = await this.DbFactory.Create(); db.employee.Add(newEmployee); await db.SaveChanges(); // Refresh list and reset the form newEmployee = new Employee(); await RefreshEmployeeList(); } async Task DeleteEmployee ( int id ) { using var db = await this.DbFactory.Create<IndexDb>(); var employeeToDelete = db.employee.FirstOrDefault(e => e.Id == id); if (employeeToDelete != null) { db.employee.Remove(employeeToDelete); await db.SaveChanges(); await RefreshEmployeeList(); } }} View Sample in GitHub

How do I add a Blazor WebAssembly project to an existing ASP.NET Core application?

Follow these steps to add a Blazor WebAssembly project to an existing ASP.NET Core application: Create a ASP.NET Core application and Blazor WebAssembly application separately. Install the Microsoft.AspNetCore.Components.WebAssembly.Server NuGet package in the ASP.NET Core application and add the Blazor WebAssembly application project reference to the ASP.NET Core application.[AspNetCoreApp.csproj] <Project Sdk=”Microsoft.NET.Sdk.Web”>    <ItemGroup>     <PackageReference Include=”Microsoft.AspNetCore.Components.WebAssembly.Server” Version=”7.0.0″ />   </ItemGroup>     <ItemGroup>     <ProjectReference Include=”..{Your Blazor App Path}” />   </ItemGroup>   </Project> Add the following configurations the Program.cs file in the ASP.NET Core app to include Blazor WebAssembly.[Program.cs] ….if (!app.Environment.IsDevelopment()){ app.UseWebAssemblyDebugging(); app.UseExceptionHandler(“/Error”); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts();} app.UseBlazorFrameworkFiles(); app.MapFallbackToFile(“index.html”); //app.MapRazorPages(); // Remove this line. app.Run(); To avoid conflicts during publishing between WebAssembly and ASP.NET Core applications, it is necessary to delete the favicon.ico file. By default, both projects create a favicon.ico file, which can lead to conflicts. To resolve this, remove one of the favicon.ico files from the project. Refer to this link for more information.  View Sample in GitHub 

How do I add authentication to a Blazor WebAssembly app?

Blazor authentication is implemented to determine who a particular user is. Blazor follows the existing ASP.NET Core authentication mechanisms to show a user’s identity.Follow these steps to implement authentication within Blazor WebAssembly: Create a Blazor WebAssembly app with individual user account authentication in Visual Studio 2019. Install the NuGet package named “Microsoft.AspNetCore.Components.WebAssembly.Authentication” using the NuGet package manager. To support the authenticating service, add the AddOidcAuthentication service configuration to the Program.cs file.[Program.cs] using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;. . .   builder.Services.AddOidcAuthentication(options =>       {         builder.Configuration.Bind(“Auth0”, options.ProviderOptions);         options.ProviderOptions.ResponseType = “code”;       }); In wwwroot/appsettings.json file, replace the Authority and Client ID placeholders with the proper values taken from the Auth0 dashboard.Note: Use Auth0; it will let you integrate authentication for configuring your application. Refer to this link for how to configure the application.[wwwroot/appsetting.json] {   “Auth0”: {     “Authority”: “https://<YOUR_AUTH0_DOMAIN>”,     “ClientId”: “<YOUR_CLIENT_ID>”   }} Add the authentication service script reference to the index.html file, which handles the low-level details of the OIDC protocol.[index.html] <body>       //. . .       <script src=”_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js”>     </script>      </body> Add CascadingAuthenticationState and AuthorizeRouteView to display the page matching the specified route only if the user is authorized. Otherwise, it redirects to the Login page.[App.razor] <CascadingAuthenticationState>     <Router AppAssembly=”@typeof(Program).Assembly”>     <Found Context=”routeData”>         <AuthorizeRouteView RouteData=”@routeData” DefaultLayout=”@typeof(MainLayout)”>             <Authorizing>                 <p>Loading…</p>             </Authorizing>             <NotAuthorized>                 <p>You’re not authorized to reach this page. You need to log in.</p>             </NotAuthorized>         </AuthorizeRouteView>     </Found>     <NotFound>                <p>Sorry, there’s nothing at this address.</p>             </NotFound> </Router> </CascadingAuthenticationState> Create a Razor component to allow the user to log in to be authenticated in the Shared folder.[Shared/LoginControl.razor] @using Microsoft.AspNetCore.Components.WebAssembly.Authentication   @inject NavigationManager UriHelper @inject SignOutSessionStateManager SignOutManager   <AuthorizeView>     <Authorized>         Hello, @context.User.Identity.Name!         <a href=”#” @onclick=”OnClickEvent”>Log out</a>     </Authorized>     <NotAuthorized>         <a href=”authentication/login”>Log in</a>     </NotAuthorized> </AuthorizeView>   @code{     private async Task OnClickEvent(MouseEventArgs args)     {         await SignOutManager.SetSignOutState();         UriHelper.NavigateTo(“authentication/logout”);     } } Reference the LoginControl page in the MainLayout.razor page.[MainLayout.razor] <div class=”main”>         <div class=”top-row px-4 auth”>             <LoginControl />             <a href=”https://docs.microsoft.com/aspnet/” target=”_blank”>About</a>         </div>           <div class=”content px-4″>             @Body         </div>     </div> Create an Authentication.razor component in the Pages folder to authenticate the user when logging in and out of the app.[Pages/Authentication.razor] @page “/authentication/{action}”@using Microsoft.AspNetCore.Components.WebAssembly.Authentication @using Microsoft.Extensions.Configuration   @inject NavigationManager UriHelper @inject IConfiguration Config   <RemoteAuthenticatorView Action=”@Action”>     <LogOut>         @{             var authority = (string)Config[“Auth0:Authority”];             var clientId = (string)Config[“Auth0:ClientId”];               UriHelper.NavigateTo($”{authority}/v2/logout?client_id={clientId}”);         }     </LogOut> </RemoteAuthenticatorView>   @code{     [Parameter]     public string Action { get; set; } } Now display the authorized content when the app is authorized. If the app is not authorized, display the “Not Authorized” message to the user.[Index.razor] @page “/”  <AuthorizeView>     <Authorized>         <h1>Hello, @context.User.Identity.Name !</h1>           <p>Welcome to your new app.</p>     </Authorized>     <NotAuthorized>         <p>Not Authorized</p>     </NotAuthorized> </AuthorizeView> Press Ctrl + F5 to run the application and click Log in in the header to authenticate the user. Refer to this documentation for more details. View Sample in GitHub