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 app | Lesson where you learned it |
|---|---|
Project, Razor, components, parameters, EventCallback | Getting Started to Components |
Layouts, NavLink, routing, @page | Layouts, Built-in Components |
EditForm, InputText, validation attributes | Forms & Events, Form Validation |
| Interactive Server, static pages for login | Server Rendering, WebAssembly & Auto |
confirm() and localStorage from C# | JavaScript Interop |
@inject, scoped services, FoodService | Dependency Injection, Services |
EF Core, DbContext, SQLite | Database Handling |
| Controllers, routes, status codes | API Integration |
| Middleware, Identity, roles, antiforgery | Application 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 file | What 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.cs | Services and the middleware pipeline |
TeaShop.http | Sample API requests |
The models are plain classes. Validation attributes on them protect both the forms and the API:
OrderItemcopies 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):
AddDbContextFactorygives each service a freshDbContextper operation, which is safe in Blazor Server (see Database Handling).SeedData.InitializeAsynccreatesteashop.dbwithEnsureCreatedAsync(), 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
MainLayoutputs the header with theNavMenuon every page, and@Bodyin the middle (see Layouts).App.razorchooses the render mode per page: account pages stay static (they set the login cookie), all others are Interactive Server.
NavLinkadds theactiveclass to the link of the current page.- The links change with the user:
AuthorizeViewshows My orders to logged-in users and the admin links only to the Admin role. The inner view getsContext="adminContext"because both views would otherwise name their parametercontext. - The cart badge updates by itself:
NavMenulistens toCartService.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 route | Who | What it does |
|---|---|---|
GET api/foods | Everyone | The menu |
GET api/foods/3 | Everyone | One item, or 404 |
POST, PUT, DELETE api/foods | Admin | Change the menu |
GET api/orders | Logged in | My orders |
POST api/orders | Logged in | Place an order |
GET api/orders/all | Admin | Every order |
PUT api/orders/5/status | Admin | Change an order's status |
- The controller gets
FoodServicethrough its primary constructor (see Dependency Injection). It does no database work itself. [ApiController]checks the[Required]and[Range]attributes ofFoodItemand answers 400 with the errors.Program.csmaps the controllers withapp.MapControllers().
- Each method asks the factory for a new
DbContextand disposes it withusing.
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:
| Line | Its 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.AddToRoleAsyncgives the user a role claim. It travels in the login cookie.
User Registration
Register.razoris a static page: the_Imports.razorinComponents/Accountadds[ExcludeFromInteractiveRouting]to every account page. A cookie can only be written on an HTTP response (see Authentication).[SupplyParameterFromForm]fillsInputfrom the posted form, andFormName="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.Errorsand 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):
ReturnUrlbrings the user back to the page they wanted, for example/checkout.SafeReturnUrlonly 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
NavMenuthat posts toaccount/logoutwith an<AntiforgeryToken />. The endpoint inProgram.cscallsSignInManager.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).
| What | How 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 |
| Forms | Antiforgery tokens (UseAntiforgery, <EditForm>, <AntiforgeryToken />) |
| Prices and quantities | Checked 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
OnInitializedAsyncruns 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
NavMenucounts 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,
CartServiceraises an event,OnChange. Components that show the cart subscribe to it and render again. They unsubscribe inDispose, 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
EditFormand theCheckoutFormmodel (see Form Validation). DataAnnotationsValidatorchecks 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
abcfails 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 toorders?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=4from the address and shows a thank-you message..Include(o => o.Items)inOrderServiceloads 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):
| Role | May do |
|---|---|
| Customer | Order, see their own orders |
| Admin | Everything a customer may do, plus manage food items and all orders |
Components/Admin/_Imports.razorputs@attribute [Authorize(Roles = SeedData.AdminRole)]on every page in that folder at once.NavMenushows 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
FoodItemwithId = 0. Edit works on a copy, so Cancel leaves the table unchanged. - Save calls
AddAsyncwhenIdis 0, otherwiseUpdateAsync. - 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.
@onchangegives the chosen value as text.Enum.TryParseturns it back into anOrderStatus.- 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.
| Folder | What 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.http | Sample API requests |
Project Setup Instructions
You need the .NET 10 SDK.
- Unzip the file and open a terminal in the
TeaShopfolder. Trust the development certificate (once per computer):
dotnet dev-certs https --trustStart the app. The first run downloads the NuGet packages and creates
teashop.db:dotnet run --launch-profile httpsOpen
https://localhost:7150and log in:Email Password Role admin@teashop.com Admin123! Admin: menu, orders, manage food and orders ravi@teashop.com Ravi1234! Customer: menu, cart, checkout, my orders
To start again with a fresh database, stop the app and delete teashop.db.
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
A component member named like its page (Cart in Cart.razor) | Any name works | Name pages CartPage.razor, MyOrders.razor | CS0542: member names cannot be the same as their enclosing type |
| Interactive login or register pages | Every page can set a cookie | Keep account pages static ([ExcludeFromInteractiveRouting]) | The login cookie is never written |
Not unsubscribing from CartService.OnChange | Events clean up by themselves | Unsubscribe in Dispose | Old components stay in memory and still render |
| Taking prices from the cart | The browser sends the right price | Read prices from the database in OrderService | Tampered requests buy food for free |
| Only hiding admin links | Hidden means protected | [Authorize(Roles = ...)] on pages and API actions | Customers open admin pages by typing the address |
Returning to any returnUrl after login | A return address is always safe | Only accept addresses on your own site | Open 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