Skip to content

scottkuhl/BlazorStaticWebApp

Repository files navigation

Azure Static Web App

This template is an example and starting point for creating a Azure Static Web App based on Blazor. It goes further than the Blazor Starter provided by Microsoft. The demo uses a basic movie list viewer with a separate lazy loaded area for administration.

TO DO

Azure

  1. Create an Azure Storage account.

  2. Create an Azure Cosmos DB account.

  3. Create an Azure Static Web App and connect it to your new repository.

  4. Update the settings in your new Azure SWA to include the storage and database connection strings. The names for these values are in the local.settings.json file in the API project.

Project Changes

  1. Update this README (title, description, user experience).

  2. Rename the solution and all instances of the application name.

  3. Use custom app icons and images.

  4. Update the privacy policy page.

Tips to Reduce Complexity

  1. Consider replacing the Resource file usage with plain text if you are only going to support one language.

  2. Remove the Lazy Loaded assemblies if the application is not large.

Production Ready Apps

Consider the following to make you application production ready:

  1. Add support channels (Discord, Email, GitHub Discussions, Reddit, Report Abuse).

  2. Add revenue (Ads, Affiliate Links, Paid Accounts, Patreon, Merchandise, Revenue Cat).

  3. Add Help (Wiki, Tango).

  4. Add communication channels (Blog, Newsletter).

Getting Started

  1. Install the latest version of Visual Studio.

  2. Setup your workstation to develop with Blazor. You will also need the .NET WebAssembly build tools optional component.

  3. Add the Azure development workload to Visual Studio.

  4. Install the Azure Static Web Apps CLI. This will launch automatically when the project is opened using the Command Task Runner extension.

  5. Install the Azure Cosmos DB Emulator. This will launch automatically if it is not already running when the project is opened using the Command Task Runner extension.

  6. Install the Markdown Editor extension. You can use this to preview markdown files like this one.

  7. Install the Command Task Runner (64-bit) extension.

  8. Install the CodeMaid extension.

  9. Enable Run Code Cleanup profile on Save in Text Editor > Code Cleanup. The clean up profile should have all options applied. Unfortunately at this time, these options can't be stored in a solution.

Optional: Setup Windows Terminal to close the process exits, fails or crashes instead of closing only when the process exits successfully. This will close the Azure Functions window when you stop debugging.

Visual Studio 2022

Once you clone the project, open the solution in Visual Studio 2022 and follow these steps:

  1. Right-click on the solution and select Set Startup Projects....

  2. Select Multiple startup projects and set the following actions for each project:

    • Api - Start
    • Client - Start
    • Shared - None
  3. Press F5 to launch both the client application and the Functions API app.

Clean Code Rules

  1. CodeMaid - The solution folder contains a basic configuration for it that will automatically apply setting on save.

  2. Roslynator - A extended collection of Rosyln analyzers is included as a NuGet package on all projects.

  3. AsyncFixer - A NuGet package included on all projects that finds and corrects common misuses of async/await.

  4. A starting .editorconfig file with minimal rule changes is included.

  5. Code styles are enforced on build.

  6. Code Cleanup on Save - Use this extension in Visual Studio to apply code cleanup rules on every save.

  7. Changes should not be committed with unresolved compiler Errors, Warning or Messages.

  8. Razor components should use code behind files.

User Experience

EXAMPLE

  • The user interface should adapt primary to mobile and tablets.

  • The voice and personality of the application should feel fun.

  • Since we will be using MudBlazor, the application will follow Material Design for the web guidelines.

  • Icons are from the Material Icon set in MudBlazor and Undraw when required.

Architecture

  • Common: Common functionality that is not application specific is located in separate projects.

  • Api: A C# Azure Functions API, which the Blazor application will call.

  • Client: The Blazor WebAssembly sample application.

  • Shared: A C# class library with a shared data model between the Blazor and Functions application.

Api

  • Cache: Basic response caching is available using a custom filter.

  • Cancellation Tokens: Cancellation tokens are used to end requests if the client cancels them.

  • Data: Cosmos DB is used to store data. A common repository is setup for shared logic. Bogus will seed test data in the local environment on startup.

    • Data (Simple): A simplified version of the data is stored in Azure Table Storage. Only very basic filtering is supported. Most paging, filtering, searching, and sorting must be done using in memory logic or storing duplicates of the data. It can however be more cost efficent than Cosmos DB.
  • Exceptions: Common custom exceptions are available. Functions inherit from a base Function class which implements global exception handling and logging which can be monitored by Application Insights.

  • Lists: List based queries support server side paging, filtering, searching, sorting and return meta data about the results as either a pagable or virtualized list.

  • Parameters: Standard query parameters are extracted from the query string.

  • Security: Authorization for functions is defined in the staticwebapp.config.json file in the Client project. Any method that requires admin access is under a /manage route. (/admin is a reserved route that can't be used)

  • Uploads: File uploads are stored in Azure Storage. The local Azurite emulator is installed with Visual Studio 2022 and the API project is configured to run it.

  • Validation: A custom model validator will deserialize and valid an model sent into the body of the request.

Client

  • AOT: Ahead-of-Time compilation is enabled on for published releases.

  • Cancellation Tokens: Cancellation tokens are passed to API calls and the request is canceled if a user navigates to another component.

  • Components: There are standard components for confirmation and notification dialogs.

  • Exceptions: There are custom 404, unauthorized, client and server pages. The HTTP Client enables an interceptor that handles any errors coming back from the server and sends them to the proper error page. Any other error thrown on a page is caught in a global error boundary on the Main Layout component and sent to the client error page. Anything that is thrown outside of all of these will trigger the error UI in the index.html page.

  • Form Submit: Double form posting can be prevented using an IsSubmitting variable.

  • Lazy Loading: The client application is broken into logical areas to speed up the initial render by lazy loading the area projects.

  • Loading: HTTP requests will show a loading bar.

  • Localization: Resource files are available for multiple language support. The default language is based on the browser, but a component is available that allows the user to change their language.

  • Navigation Menu: The side navigation switches to include bottom navigation on smaller screens.

  • Privacy: A sample privacy page is included as well as a GDPR cookie compliance banner.

  • Progessive Wep App: A starting manifest and service worker is setup that mirrors the default PWA template configuration but with Skip Waiting setup. Skip Waiting ensures that any new versions of a service worker will take over the page and become activated immediately. The SWA based authentication paths (/.auth/) have been excluded from caching.

  • Security Headers: Some headers have been added to make the application more secure by default. These are configured in the staticwebapp.config.json file in the Client project.

    • Content-Security-Policy: Default to allowing HTTPS and localhost. 'unsafe-inline' 'unsafe-eval' are allowed for WASM compilation, Blazor compatibility and Hot Reload. Objects are not allowed.
    • Referrer-Policy: Set to send no referrer information.
    • Strict-Transport-Security: Expires in one year, applies to all sub-domains, allows submission to Google's HTST Preload list.
    • X-Frame-Options: Set to deny the site from loading in a frame.
  • Timeout: HTTP client requests use a simple retry policy for failed network connections.

Shared

  • DTOs: Data Transfer Objects are used as needed to return lists of data.

  • Exceptions: When exceptions happen in the API layer, a custom ErrorDetails class is returned.

  • Models: Models inherit from a common base Model class.

  • Parameters: Standard query parameters that can be passed to list based API requests.

  • Sanitizing: Models should sanitize there input for HTML.

  • Services: A date / time and guid service are available to make automated testing easier.

  • Validation: If an invalid model is passed in a InvalidResults class is returned.

Reference

These references are presented in a logical order for review from start to finish for gathering a deeper understanding of the code base. There is an assumption that you are already familiar with C# and ASP.NET Core.

Books & Series

  • Microsoft Blazor: Building Web Applications in .NET 6 and Beyond: Reading this book helps you learn to build user interfaces and present data to a user for display and modification, capturing the user’s changes via data binding. The book shows how to access a rich library of .NET functionality such as a component model for building a composable user interface, including how to develop reusable components that can be used across many pages and websites. Also covered is data exchange with a server using REST, SignalR, and gRPC, giving you access to microservices and database services.

  • Ultimate ASP.NET Core Web API: Second Edition of Code Maze's complete, hands-on, and easy to digest program that gets you from zero to building production-ready APIs in just a few weeks.

  • Blazor WebAssembly - A Practical Guide to Full Stack Development With .NET: The lessons start with the basic concepts of building a simple but practical application with Blazor WebAssembly. We cover all the things we need in order to build a real-world application and we quickly transition to building full-fledged application parts, slowly introducing the concepts as we go.

  • Guide to NoSQL with Azure Cosmos DB: By the end of the book, you will be able to build an application that works with a Cosmos DB NoSQL document database with C#, the .NET Core SDK, LINQ, and JSON.

  • Blazor Train: Blazor Train is an extensive class on Microsoft Blazor, an extremely productive technology for developing web applications using HTML markup and the C# programming language.

  • 30 Days of SWA: Simply put, it's a month-long series of blog posts that provides you a curated and structured tour through the universe of Azure Static Web Apps.

Articles & Videos

Documentation

  • Blazor WebAssembly: Blazor is a framework for building interactive client-side web UI with .NET.

  • MudBlazor: MudBlazor is an ambitious Material Design component framework for Blazor with an emphasis on ease of use and clear structure.

  • Azure Static Web Apps: Azure Static Web Apps allows you to build modern web applications that automatically publish to the web as your code changes.

  • Static Web Apps CLI: The Static Web Apps (SWA) CLI is an open-source commandline tool that streamlines local development and deployment for Azure Static Web Apps.

  • Azure Functions: Azure Functions is a cloud service available on-demand that provides all the continually updated infrastructure and resources needed to run your applications. You focus on the pieces of code that matter most to you, and Functions handles the rest. Functions provides serverless compute for Azure. You can use Functions to build web APIs, respond to database changes, process IoT streams, manage message queues, and more.

  • Azure Cosmos DB: Fast NoSQL database with SLA-backed speed and availability, automatic and instant scalability, and open-source APIs for MongoDB and Cassandra.

  • Azure Blob Storage: Azure Blob Storage is Microsoft's object storage solution for the cloud. Blob storage is optimized for storing massive amounts of unstructured data.

Other

About

Blazor Azure Static Web App Example

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published