- Getting started – project set up
- Project walk through
Hello! Today I will be showing you how to get started from scratch with .NET Core’s Blazor Server. If you want to understand Blazor Server more, Microsoft have some really good documentation here if you wanted to understand that before getting started 😊
The first part of this guide will be a simple tutorial on setting up a Blazor project and then the second part will be explaining the different files in the project in more detail.
Getting started – project set up
Right, so lets first create the solution that Blazor will live in – I will then do a tour around what a Blazor project consists of and any tips etc. I will be also using Visual Studio 2019 on Windows 11 all the way through.
Open visual studio and hit Create a new project
Enter “Blazor” (1) in the search bar, click “Blazor Server App” (2) and finally click “Next” (3)
The next page is to set the project name and where you want to store this – these settings are up to you 😉 Once done just hit Next.
4 – Now this next page in the wizard is an interesting one – I have popped a couple of explanations below if you want recommendations on what to select but for this guide I am leaving everything as their defaults.
The target framework (as of when I am writing this post) is up to you, but I would recommend .NET 5. If .NET 6 is available by the point you are reading this – go with that instead as it has long term support!
As Blazor sits on .NET Core it also has the ability to have the ASP.NET Core Identity authentication created with it – this gives the application out of the box authentication functionality with user accounts etc. For this guide you won’t need to select anything here but I thought it is worth mentioning if you required authentication in your applications 😊
Once happy, hit Create
Project walk through
Congrats! You’ve created your Blazor Server project, now the fun bit begins! 🥳
I will be throwing around a few tips here and there as part of this, but please don’t feel obliged to follow them – they are just things that have helped me when I’m developing my own Blazor apps 😊
Now you can choose to use IIS or Kestrel for running you apps locally. These are super easy to switch between if you need to for any reason. I personally use Kestrel and this is purely for the reason that… it gives you a console when the app is running! If you want to switch over to Kestrel from the get go click the IIS Express debug button dropdown and select your project name
Whether you chose IIS or Kestrel, either way just give your solution an initial build and lets fire it up! 🔥
If you chose Kestrel you will get a console show up + the web app loaded up in the browser with the classic Hello World screen!
And that’s all you need to do to run your app – simple right? 😎
Now lets take a look at the project structure itself and walk through a few files that are worth noting – I will try and walk through these at the time they are executed to help make it flow nicely.
The app settings are a standard .NET Core thing and are what store various configuration values for the Blazor app. In general the app settings files are very useful for storing application level configuration such as log levels, static email addresses, if something is disabled or enabled and so on… pretty much anything! You have multiple app setting files that are environment specific so you can use different configs for each environment. For more info on the appsettings.json file and how to use them per environment then please see here.
🚫Do not store your secrets here! 🚫
Please remember not to store secrets, keys or connection strings in app settings directly – that is a BIG no no for security! For local development you should use User Secrets which is a built in with .NET Core for storing secrets and keys locally on your machine and not in source. For hosted apps I recommend using Azure Key Vault if you are deploying your apps on the Azure platform – which I also recommend. 😉
You may or may not be familiar with Program.cs as it’s quite a common file across .NET. The importance of this file is that as soon as you fire up your app, this is the first bit of code that is hit.
It’s pretty self explanatory in the Main() method but inside here we are executing the CreateHostBuilder() method, which is the bit of code that triggers your “Startup” code – by default this is the Startup class held in Startup.cs – this is the file where the majority of your Blazor related set up is done.
Startup.cs is the file where you do most of your Blazor configuration – for example if you have installed a third party NuGet package such as Serilog then you will be required to “register” this in Startup.cs so Blazor can use it.
By default the services to get the application up and running from the get go are already present in here. Any other packages you install will give you a guide on how to register their services and what to put in the ConfigureServices() and Configure() methods so they can be used in Blazor.
Some other things that can be configured (but not limited to) in startup are:
- Database contexts
- Database migrations
- Identity defaults i.e. password requirements
- Custom data services (for access to your own databases)
- Registering third party NuGet packages
That’s it for the CSharp-y files that are used during firing up the application. The next lot of files are Blazor specific and involve things such as routing and the UI.
This file is a general C# html file for the web, it contains the head and body tags that all the Blazor stuff gets rendered inside. This works the same way as standard HTML so amend this as you wish with CSS and JS scripts.
This file also has some Blazor things in the Body tag such as the <component> tag which defines the root component of the application, which by default is the App.razor component which we will explain later on.
This also handles what is displayed in the event of an exception occuring in the app, all of this is controlled in the div containing the blazor-error-ui id.
This is the area which stylesheets and application images should go that need to be publicly accessible. By default the bootstrap css and open iconic icons are installed alongside a site.css which contains the initial styling classes for the default blazor app.
Razor components overview
We are now in the UI side of things where razor files take over in the form of components. These are essentially blocks of HTML style code you can place onto a page, with the difference of that when the page attempts to render a component onto the screen, the components internal C# code is executed. They are awesome for re-usability, as you can use the same component over and over and over! 😎
This component is the root component of the application and is therefore the first component executed when the user wants to go to another page. The <Router> component is a .NET Core framework component that does all of the routing for us, however if you are feeling ambitious you can also create your own router if you have specific use cases – but lets leave that for another day! 😉
There are a couple of other components nested inside the Router that are worth noting – if the component the user wants to navigate to exists then another framework component <Found> is executed – otherwise the <NotFound> component is executed instead, you can see this actually displays some text saying “Sorry, there’s nothing at this address.”
You will have noticed the class MainLayout is referenced a lot in App.razor, which I will explain next.
Providing a component exists, the App.razor component will route through to the MainLayout component which is well… the main layout of the screen. This is where the sidebar and body are outputted so they are rendered on screen as you can see below.
@Body will render the page you are navigating to, so if navigating to “/” which is the Index.razor component by default then the index component is rendered where @body is defined. But how do we know what a components URL is you ask? I will cover this in the next section.
Razor components are mostly all structured in the same way, I have modified my Index.razor component page to have some additional methods in to showcase.
In order to define what URL the component is accessible by, this is defined as @page and then followed by any HTML or nested components you want to display on the screen.
The lifecycle of a razor components is well documented by Microsoft here if you want a more in depth view of what each .NET method is to be used for and when.
A method I use in almost all of my components is OnInitializedAsync() as this is primarily used for initializing your component with what it needs and to perform conditional logic. The OnAfterRenderAsync() method can be pretty useful too but the use cases are more limited. I tend to code my applications asynchronously hence using Async methods – but synchronous methods are also available such as OnInitialized() if that’s what floats your boat.⛵
Lets say you have a razor component sitting in a completely separate project in your solution – obviously to link this project to your Blazor web project you add a project reference and you are done. However, there is another step in Blazor as you have to add an @using reference to each and every component to tell it where to pick up this new component – such as the below.
Painful right? 😟 Luckily the whole @using repetition can be totally avoided by using _Imports.razor and once the reference is popped in here ALL components in that project can pick it up – problem solved! 😊
Once the reference is in _Imports.razor, you no longer need to reference it in each of your components and your new component can still be found by magic!
Those who love tidy code, this one is for you. 😉
Well that’s the end of this tutorial! Hopefully you now have a good idea of how to set up a Blazor Server project and the function of each of the files around the project.
If you have any questions or feedback please don’t hesitate to contact me, I’ll be happy to assist! 😊
If you have some spare time, please check out my development services at Orionfinity 😊