How do I get the page referrer in Blazor?

To get the page referrer of where the user came from, follow these steps: Create a JavaScript function as a separate file in your application (~/wwwroot/interop.js). function getPageReferrer()  {     return document.referrer; } Add the script reference in the ~/wwwroot/index.html file of the Blazor WebAssembly application. <script src=”interop.js”></script> Invoke the JavaScript function using the IJSRuntime service in a Razor page. @page “/” @inject IJSRuntime JSRuntime @code { protected override async Task OnInitializedAsync() { var pageReferrer = await JSRuntime.InvokeAsync(“getPageReferrer”); } } View Sample in GitHub

How do I deploy a Blazor WebAssembly application to GitHub pages?

Follow the steps below to deploy a Blazor WebAssembly application to GitHub Pages. Prerequisites: .NET Core 3.1/.NET 5.0GITGitHub Account Create a Blazor WebAssembly project using the below command in the CLI. mkdir BlazorGitHubPagesDemocd BlazorGitHubPagesDemodotnet new blazorwasm Add the .gitignore file to ignore the bin/obj files. dotnet new gitignore Now, create a new GitHub repository according to GitHub’s instructions and run the following commands in the CLI to push an existing repository to the created GitHub repository page. // Create the Git repository git init // Track all files that are not ignore by .gitignore git add –all // Commit all changes to the repository git commit -m “Initial commit” // Push the changes to the existing repo master branch git remote add origin https://github.com/{{GitHub_User_Name}}/BlazorGitHubPagesDemo.git git push -u origin master Now the changes have been committed in the newly created GitHub repository. After the source code has been pushed to the created GitHub repository, create a new GitHub action workflow to build the project, commit the output, and push the published code to a separate branch. To deploy in GitHub, GitHub Pages will use a separate branch (named gh-pages) as the static files for your site. To achieve this, navigate to the Action tab in the GitHub repository and click the set up a workflow yourself option to create a new GitHub workflow action. Clicking set up a workflow yourself will navigate to the Edit new file page. This file will instruct GitHub actions to build and deploy your project using YAML. Refer to “GitHub Actions” for the workflow of YAML files. Copy this code and paste it in your YML file. [main.yml] Now that all steps are in place, commit the file. Navigate back to the GitHub Actions overview page by clicking the Actions tab. You can now find your GitHub Action Workflow and the workflow runs on this page. Click on the first run that was automatically created when you committed the workflow, and watch it publish your project to the gh-pages branch. Once completed, you can see the result by navigating to the gh-pages branch in your repository. To enable GitHub pages in the repository settings, navigate to the settings by clicking on the Settings tab. Scroll down to the “GitHub Pages” section and select the gh-pages branch in the Source dropdown. Now, the GitHub Pages site should be available at in the below link. ‘[YOUR_USERNAME].github.io/[YOUR_REPOSITORY_NAME]’. Refer to “How to deploy ASP.NET Blazor WebAssembly to GitHub Pages” for more details.

How do I unit test a Blazor component?

Unit testing is a level of software testing that is used by developers to ensure that the implemented logic meets the requirements and behaves as expected. The following example uses the bUnit testing library for Blazor components to write comprehensive and stable unit test cases. It allows you to write test cases in C# or Razor syntax to verify outcomes with semantic HTML diffing and comparison logic. Create a simple Blazor Server/WebAssembly application. In Visual Studio 2019, right-click on the project solution and select the Add > New Project option. Select NUnit Test Project (.NET Core) and click Next button. Enter the project name and then click Create button. The created project will be displayed like the following. Open the NuGet manager for BlazorTest and search with the keyword bunit.web. The result will be displayed as seen in the following screenshot. Select bunit.web and install it. Right-click on BlazorTest project dependencies and add the project reference BlazorServerApp. Now, write a test case for a Razor component. Add a Razor component to your Blazor project. [Index.razor] @page “/”   <h3>Hello World</h3>   <button class=”btn btn-primary” @onclick=”OnButtonClick”>Ping Me</button>   @if (IsVisible) {     <h5>Blazor component is clicked.</h5> }   @code {       public bool IsVisible { get; set; }     protected void OnButtonClick()     {         IsVisible = true;     } } Add the following test cases in your created test project file [UnitTest1.cs] to test the Blazor components. [UnitTest1.cs] using NUnit.Framework; using Bunit;   namespace TestProject1 {     public class Tests     {         [SetUp]         public void Setup()         {         }           [Test]         public void Test1()         {             // Arrange             using var context = new Bunit.TestContext();               // Act             var cut = context.RenderComponent<BlazorServerApp.Pages.Index>();             cut.Find(“button”).Click();               // Assert             cut.Find(“h5”).MarkupMatches(“<h5>Blazor component is clicked.</h5>”);         }     } } Then select the View > Test Explorer options in Visual Studio 2019 and run the test. Now you will see the list of test methods. The test run is successful, and the test case passes. You can also alter the test case if it fails. Refer to “Unit test a Blazor component” for more details and download the sample here.

How do I prerender a Blazor WebAssembly application to static files?

Blazor prerendering is a process where web page elements are built and compiled on the server and static HTML is hosted in WebAssembly (client side). When Razor pages load, components are prerendered at the same time. This process improves page loading by making it faster for SPAs (single page applications), which improves search engine optimization. To set up prerendering for a hosted Blazor WebAssembly app: Create the Blazor web Assembly App with ASP.net core Hosted. Here solution name is BlazorHosted. Delete wwwroot/index.html file from the Blazor WebAssembly Client project. In the Client project, delete the following lines in Program.cs: – builder.RootComponents.Add<App>(“#app”);- builder.RootComponents.Add<HeadOutlet>(“head::after”); Add the _Host.cshtml and _Layout.cshtml files to the Pages folder in the Server project. These files are already included in the Blazor Server template and can be obtained from there.Make the following changes to the _Host.cshtml file: Modify the namespace based on APP namespace as BlazorHosted.Client. Update the render-mode as ‘WebAssemblyPrerendered’ in host.cshtml <component type=”typeof(App)” render-mode=”WebAssemblyPrerendered” /> Make the following changes to the _Layout.cshtml file:Update the Pages namespace at the top of the file to match namespace of the Server app’s pages like this, @namespace BlazorHosted.Server.Pages Add @using directive for the Client project at the top of the file: @using BlazorHosted.Client Update the stylesheet links to point to the WebAssembly project’s stylesheets. So, make the following changes.Remove the following lines <link href=”css/site.css” rel=”stylesheet” /><link href=”{App Name space}.styles.css” rel=”stylesheet” /><component type=”typeof(App)” render-mode=”ServerPrerendered” /> Add the following lines <link href=”css/app.css” rel=”stylesheet” /><link href=”BlazorHosted.Client.styles.css” rel=”stylesheet” /><component type=”typeof(App)” render-mode=”WebAssemblyPrerendered” /> Modify the Blazor script source of Server side Blazor: <script src=”_framework/blazor.webassembly.js”></script> In the endpoint mapping of the Server project in Program.cs, update the fallback from the index.html file to the _Host.cshtml page.Remove the following line app.MapFallbackToFile(“index.html”); Add the following line app.MapFallbackToPage(“/_Host”); If the Client and Server projects use one or more common services during prerendering, factor the service registrations into a method that can be called from both projects. For more information, see ASP.NET Core Blazor dependency injection. Run the Server project. The hosted Blazor WebAssembly app is prerendered by the Server project for clients. View Sample in GitHub 

How do I deploy a Blazor Server application to Azure App Service?

Follow the steps below to deploy a Blazor Server application to Azure app service. Create a Blazor Server application To create a blazor Server Application using the following steps Open Visual Studio 2019 and create a new project. Once Blazor App is selected, click Next button to configure the project name and location. Save the application, and then click Create. Select Blazor Server App and click Create to complete the application creation. Deploying to Azure app service To Deploying the Azure App Service using the following steps. If you don’t have a login for Azure, sign up to access the Azure portal. Click Create a resource in Azure to create a resource group. Select the Web App Azure application service. Once Web App is selected, select the following options: Select Free Trial as the subscription. Create a resource group name, such as “Blazor.” Update the Instance Details: Name: blazor-publish. The application hosted will be available in this URL: blazor-publish.azurewebsites.net. Select the Code radio button for Publish. Choose the .NET Core 3.1 LTS runtime stack and Windows operating system. Select the region in which to publish the app. Central US was chosen for this demo. The app service plan with the Free F1 option will be selected by default, but this can be modified. Once this is done, click Review + create. After configuring the Web App Service, get the publish profile for the Web App Service to host the Blazor Server application. Select the created web app service (blazor-publish). Navigate to the overview section and click Get publish profile, and the save the profile locally. Publish a Blazor Server application in Azure Using import-profile option To using import-profile option using the following steps. Right-click the project and click Publish in the context menu. Choose Import Profile and click Next button. Then, locate the downloaded publish profile for the web app service. Finally, publish the application by clicking Publish. The application will be deployed and will be available in the URL https://blazor-publish.azurewebsites.net/. Using Azure account login To using Azure account login using the following steps. In Visual Studio 2019, right-click on the project and click Publish in the context menu. Select Azure as the target. Select Azure App Service (Windows) as the specific target. You need to log in to your Azure account and choose the web app service. Now click publish to deploy the application. Now, the application will be deployed and will be available in the following URL. https://blazor-publish.azurewebsites.net/ Refer to “Publish an ASP.NET Core app to Azure with Visual Studio” for more details.