Capstone Project - Tea Shop

By Syncfusion®, Inc. · Last updated

Build Tea Shop, a complete food ordering app: project setup, layout and navigation, a Web API, ASP.NET Core Identity with registration, login and logout, secured pages and APIs, a menu, a shared cart service, checkout with validation, order history, roles and admin pages for food items and orders.

What you will learn

  • Combine components, layouts, forms, services and EF Core in one app
  • Build a Web API that shares services with the Blazor pages
  • Add Identity registration, login, logout and role-based authorization
  • Build a shared cart, checkout, order history and admin pages

Project Overview

In this lesson, you build Tea Shop: a real food ordering website. Customers order tea and snacks; the shop's admin manages the menu and the orders. It brings together everything from this course in one project.

Real-World Example

Ravi opens the Tea Shop, adds two Masala Chai and a Samosa to his cart, logs in, types his address and places the order. In the kitchen, Meena (the admin) sees the new order, marks it Preparing, then Delivered. Ravi sees the new status in My orders. Meena also adds a new snack to the menu.

Animation: a dot follows the user journey. Menu, then Cart, then Log in, then Checkout, then My orders. Below, the admin path: Manage orders and Manage food.

Menu

Cart

Log in

Checkout

My orders

Customer (Ravi)

Manage orders

Manage food Admin (Meena)

status

The customer journey on top, the admin’s pages below.

What the finished app can do:

  • Show the menu with a category filter, and add items to a cart.
  • Register, log in and log out with ASP.NET Core Identity.
  • Place orders with a validated form, and see the order history.
  • Let admins add, edit and delete food items, and change order statuses.
  • Offer a Web API (api/foods, api/orders) protected by roles.
Part of the appLesson where you learned it
Project, Razor, components, parameters, EventCallbackGetting Started to Components
Layouts, NavLink, routing, @pageLayouts, Built-in Components
EditForm, InputText, validation attributesForms & Events, Form Validation
Interactive Server, static pages for loginServer Rendering, WebAssembly & Auto
confirm() and localStorage from C#JavaScript Interop
@inject, scoped services, FoodServiceDependency Injection, Services
EF Core, DbContext, SQLiteDatabase Handling
Controllers, routes, status codesAPI Integration
Middleware, Identity, roles, antiforgeryApplication Security chapter

Project Setup

The project starts from the Blazor Web App template, with two NuGet packages for the database and Identity:

Click Next to see each command.

The finished project has these folders:

Folder or fileWhat it contains
Models/FoodItem, Order, OrderItem, CheckoutForm
Data/AppDbContext (EF Core + Identity tables), ApplicationUser, SeedData
Services/FoodService, OrderService, CartService
Controllers/The Web API: FoodsController, OrdersController
Components/Layout/MainLayout, NavMenu
Components/Pages/Menu (Home), cart, checkout, my orders, not found
Components/Account/Register and log in (static pages)
Components/Admin/Manage food, manage orders (Admin role only)
Components/Shared/FoodCard, RedirectToLogin
Program.csServices and the middleware pipeline
TeaShop.httpSample API requests

The models are plain classes. Validation attributes on them protect both the forms and the API:

  • OrderItem copies the food name and price. If the admin changes a price later, old orders still show what the customer paid.

AppDbContext holds the tables. Because it inherits IdentityDbContext, the Identity tables (users, roles) live in the same database:

Program.cs registers everything (see Dependency Injection) and builds the pipeline (see Middleware Pipeline):

  • AddDbContextFactory gives each service a fresh DbContext per operation, which is safe in Blazor Server (see Database Handling).
  • SeedData.InitializeAsync creates teashop.db with EnsureCreatedAsync(), the two roles, two demo users and the menu. For a growing app, switch to migrations (dotnet ef migrations add ...).

The code boxes on this page run small versions of each part in your browser, with in-memory stand-ins (MemoryFoodService, MemoryOrderService) instead of the database. The complete project, with SQLite and Identity, is in the download at the end.

Layout and Navigation

  • MainLayout puts the header with the NavMenu on every page, and @Body in the middle (see Layouts).
  • App.razor chooses the render mode per page: account pages stay static (they set the login cookie), all others are Interactive Server.
  • NavLink adds the active class to the link of the current page.
  • The links change with the user: AuthorizeView shows My orders to logged-in users and the admin links only to the Admin role. The inner view gets Context="adminContext" because both views would otherwise name their parameter context.
  • The cart badge updates by itself: NavMenu listens to CartService.OnChange (see Cart below).

In the below example, the menu page uses the real FoodCard component: a [Parameter] for the food and an EventCallback that tells the parent "add this". Use the filter and the buttons.

Building the API

The same services also power a Web API, so other apps (a phone app, a WebAssembly client) can use the shop too (see API Integration).

Method and routeWhoWhat it does
GET api/foodsEveryoneThe menu
GET api/foods/3EveryoneOne item, or 404
POST, PUT, DELETE api/foodsAdminChange the menu
GET api/ordersLogged inMy orders
POST api/ordersLogged inPlace an order
GET api/orders/allAdminEvery order
PUT api/orders/5/statusAdminChange an order's status
  • The controller gets FoodService through its primary constructor (see Dependency Injection). It does no database work itself.
  • [ApiController] checks the [Required] and [Range] attributes of FoodItem and answers 400 with the errors.
  • Program.cs maps the controllers with app.MapControllers().
  • Each method asks the factory for a new DbContext and disposes it with using.

Test the API with the TeaShop.http file in Visual Studio or VS Code while the app runs:

Click Next to see each request.

Authentication Setup

The shop uses ASP.NET Core Identity with the cookie scheme (see Authentication). These lines in Program.cs set it up:

LineIts job
AddCascadingAuthenticationState()Every component can get the user as Task<AuthenticationState>
AddAuthentication(...).AddIdentityCookies()The cookie schemes Identity uses
ConfigureApplicationCookie(...)Where to send users who must log in (/account/login) or who are not allowed (/access-denied)
AddIdentityCore<ApplicationUser>(...)Users, password rules and lockout after 5 wrong tries
.AddRoles<IdentityRole>()Role support: Admin and Customer
.AddEntityFrameworkStores<AppDbContext>()Save users and roles with EF Core
.AddSignInManager()Log in and out (writes and deletes the cookie)

ApplicationUser adds one field to Identity's user, and SeedData creates the roles and the demo accounts:

  • UserManager.CreateAsync(user, password) hashes the password (see Password Storage). Only the hash is saved.
  • AddToRoleAsync gives the user a role claim. It travels in the login cookie.

User Registration

  • Register.razor is a static page: the _Imports.razor in Components/Account adds [ExcludeFromInteractiveRouting] to every account page. A cookie can only be written on an HTTP response (see Authentication).
  • [SupplyParameterFromForm] fills Input from the posted form, and FormName="register" names the form (see Forms & Events).
  • [Compare] checks that both passwords match.
  • Identity's password rules (8+ characters, a digit, an uppercase letter, a symbol) come back as result.Errors and are shown at the top.
  • New users always get the Customer role. Nobody can make themselves an admin.

User Login and Logout

Login.razor is static too. It checks the password with PasswordSignInAsync, which also counts wrong tries (lockout):

  • ReturnUrl brings the user back to the page they wanted, for example /checkout.
  • SafeReturnUrl only accepts addresses on this site. Otherwise an attacker could send users a login link that ends on a fake site (an open redirect).
  • Logout is a form in NavMenu that posts to account/logout with an <AntiforgeryToken />. The endpoint in Program.cs calls SignInManager.SignOutAsync(), which deletes the cookie.

Three rows. Register: the form posts to Register.razor, UserManager.CreateAsync saves the user with a password hash, and SignInAsync writes the cookie. Log in: Login.razor, PasswordSignInAsync checks the hash and writes the cookie. Log out: the NavMenu form posts to account/logout, and SignOutAsync deletes the cookie.

Register

CreateAsync + AddToRoleAsync + SignInAsync

cookie written

Log in

PasswordSignInAsync (checks the hash)

cookie written

Log out

POST account/logout + token → SignOutAsync

cookie deleted

Register, log in and log out, as the Tea Shop does them.

Securing Pages and APIs

The shop protects every private part twice: on the page and on the API (see Authorization).

WhatHow it is protected
Checkout and My orders@attribute [Authorize]
Every admin page[Authorize(Roles = SeedData.AdminRole)] in Components/Admin/_Imports.razor
OrdersController[Authorize] on the class, [Authorize(Roles = ...)] on admin actions
Changing the menu by API[Authorize(Roles = SeedData.AdminRole)] on POST, PUT, DELETE
FormsAntiforgery tokens (UseAntiforgery, <EditForm>, <AntiforgeryToken />)
Prices and quantitiesChecked again in OrderService on the server

Routes.razor uses AuthorizeRouteView. Logged-out users go to the login page; logged-in users without the right role see "Access denied":

Hiding the admin links in NavMenu is only for a tidy screen. The real protection is [Authorize] on the pages and on the API. Try it: log in as Ravi and type /admin/foods in the address bar.

Home Page

The home page (Components/Pages/Home.razor) loads the menu in OnInitializedAsync (see Component Lifecycle), filters it by category and shows one FoodCard per item. You ran a small version of it in Layout and Navigation. In the project, the services come from @inject:

  • With Interactive Server, the page is prerendered first, so OnInitializedAsync runs twice (see Server Rendering). For a short menu that is fine.
  • @key="food.Id" keeps each card matched to its item when the filter changes the list.

Cart (State Management)

  • State is data the app remembers while the user works, like the items in the cart.
  • Several components need the cart at once: the menu adds to it, the badge in NavMenu counts it, the cart page and checkout show it.
  • So the cart lives in one scoped service, CartService (see Services). In Blazor Server, "scoped" means one cart per user connection, shared by all components of that user.
  • When the cart changes, CartService raises an event, OnChange. Components that show the cart subscribe to it and render again. They unsubscribe in Dispose, so a closed page is not kept alive.
  • The cart is also saved in the browser's localStorage with ProtectedLocalStorage (JS interop under the hood), so it survives a reload and the static login page.

Animation: CartService in the middle. Home adds an item; an OnChange signal goes out to NavMenu (badge), the Cart page and Checkout; a save arrow goes to localStorage in the browser.

CartService scoped, one per user

Home: Add

NavMenu badge

Cart page

Checkout

localStorage

OnChange

One shared cart. Every component that shows it hears OnChange.

In the below example, CartBadge and CartView are two separate components. Neither knows the other, but both use the same CartService and listen to OnChange. Add items and change the quantities.

Placing Orders (Forms and Validation)

  • Checkout is a form for the customer's name, phone and address, built with EditForm and the CheckoutForm model (see Form Validation).
  • DataAnnotationsValidator checks the attributes in the browser and shows friendly messages.
  • On submit, the page sends the form and the cart lines to OrderService.PlaceOrderAsync. The service checks the form again, and takes every price from the database (see Server-Side Validation). The cart only sends food ids and quantities.

Animation: the checkout form sends name, phone, address and the cart lines (food id and quantity only). OrderService checks the form again, reads the prices from the database, saves the order, and the user lands on My orders.

Checkout form + ids, quantities

OrderService 1. validate again 2. prices from the database 3. save the order

teashop.db

My orders

Prices never come from the browser. The server sets them.

In the below example, the cart already holds two Masala Chai and a Samosa. Click Place order with empty fields to see the validation, then fill them in.

  • A phone like abc fails the [RegularExpression] rule, so the form is not sent.
  • The real page reads the user id from the cascading Task<AuthenticationState>: user.FindFirstValue(ClaimTypes.NameIdentifier), then clears the cart and navigates to orders?placed=4.

Order History

My orders (Components/Pages/MyOrders.razor) shows only the orders of the logged-in user. The query filters by the user id from the authentication state, never by an id from the address bar:

  • [SupplyParameterFromQuery] reads ?placed=4 from the address and shows a thank-you message.
  • .Include(o => o.Items) in OrderService loads the order lines together with the orders (see Database Handling).

In the below example, Ravi's orders are listed with their items and status.

Role-Based Authorization

The shop has two roles (see Authorization):

RoleMay do
CustomerOrder, see their own orders
AdminEverything a customer may do, plus manage food items and all orders
  • Components/Admin/_Imports.razor puts @attribute [Authorize(Roles = SeedData.AdminRole)] on every page in that folder at once.
  • NavMenu shows the admin links with <AuthorizeView Roles="Admin">.
  • The API checks the same role with [Authorize(Roles = SeedData.AdminRole)].

In the below example, the pretend provider from Authentication logs in Ravi (Customer) or Meena (Admin). The menu links and the pages follow the role. Try Manage food as each user.

  • Meena sees the Manage food button and the page. Ravi does not see the button, and if he still opens the page, he gets "Access denied".

Admin Pages

Managing Food Items

Manage food (/admin/foods) lists every item and lets the admin add, edit and delete them with one EditForm:

  • Add creates an empty FoodItem with Id = 0. Edit works on a copy, so Cancel leaves the table unchanged.
  • Save calls AddAsync when Id is 0, otherwise UpdateAsync.
  • Delete first asks with the browser's own confirm() box, called through JS interop: await JS.InvokeAsync<bool>("confirm", ...).
  • Unticking On the menu hides an item from customers without deleting it.

In the below example, the same page runs with MemoryFoodService. The code box asks "Delete? Yes / No" on the page instead of the browser's confirm() box. Add a new item, edit a price, then delete something.

Managing Orders

Manage orders (/admin/orders) shows every customer's orders. The kitchen changes the status with a <select>: Placed → Preparing → Ready → Delivered (or Cancelled). The Open filter hides finished orders.

  • @onchange gives the chosen value as text. Enum.TryParse turns it back into an OrderStatus.
  • Ravi sees the new status the next time he opens My orders.

In the below example, change the status of an order. Delivered orders leave the Open list.

Ideas to extend the project on your own: an image for each food item, a "Reorder" button in My orders, email confirmation with Identity's email sender, a sales dashboard for the admin, or migrations instead of EnsureCreatedAsync.

Download Project Files

Download Tea Shop Project Source Code

Download blazor-tea-shop.zip

The ZIP file contains the complete Tea Shop project: Blazor pages, the Web API, EF Core with SQLite, and ASP.NET Core Identity with roles.

FolderWhat it contains
Components/Layout, navigation, pages, account pages, admin pages
Controllers/FoodsController, OrdersController
Services/FoodService, OrderService, CartService
Data/AppDbContext, ApplicationUser, SeedData
Models/FoodItem, Order, OrderItem, CheckoutForm
TeaShop.httpSample API requests

Project Setup Instructions

You need the .NET 10 SDK.

  1. Unzip the file and open a terminal in the TeaShop folder.
  2. Trust the development certificate (once per computer):

    dotnet dev-certs https --trust

  3. Start the app. The first run downloads the NuGet packages and creates teashop.db:

    dotnet run --launch-profile https

  4. Open https://localhost:7150 and log in:

    EmailPasswordRole
    admin@teashop.comAdmin123!Admin: menu, orders, manage food and orders
    ravi@teashop.comRavi1234!Customer: menu, cart, checkout, my orders

To start again with a fresh database, stop the app and delete teashop.db.

Common mistakes

MistakeWrong ideaCorrect ideaWhat goes wrong
A component member named like its page (Cart in Cart.razor)Any name worksName pages CartPage.razor, MyOrders.razorCS0542: member names cannot be the same as their enclosing type
Interactive login or register pagesEvery page can set a cookieKeep account pages static ([ExcludeFromInteractiveRouting])The login cookie is never written
Not unsubscribing from CartService.OnChangeEvents clean up by themselvesUnsubscribe in DisposeOld components stay in memory and still render
Taking prices from the cartThe browser sends the right priceRead prices from the database in OrderServiceTampered requests buy food for free
Only hiding admin linksHidden means protected[Authorize(Roles = ...)] on pages and API actionsCustomers open admin pages by typing the address
Returning to any returnUrl after loginA return address is always safeOnly accept addresses on your own siteOpen redirect to an attacker's site

Check Yourself

Exercises

What to Remember

  • A real Blazor app combines everything: components with parameters, a layout with navigation, forms with validation, services with DI, EF Core, a Web API and security.
  • Keep database work in services. Pages and API controllers both use them.
  • Share app-wide state (the cart) in a scoped service with an OnChange event. Unsubscribe in Dispose.
  • Identity gives you users, roles and safe passwords. Keep account pages static, so they can write the cookie.
  • Protect every private page and API with [Authorize]; use roles for admin areas. Hidden links are not protection.
  • Validate on the server and take prices from the database.

Next: Cheat Sheet