When to use Blazor

Blazor is a fully featured web UI framework designed to handle the needs of most modern web apps. But whether Blazor is the right framework for you depends on many factors.

You should consider using Blazor for web development if:

  • You’re looking for a highly productive full stack web development solution.
  • You need to deliver web experiences quickly without the need for a separate frontend development team.
  • You’re already using .NET, and you want to apply your existing .NET skills and resources on the web.
  • You need a high-performance and highly scalable backend to power your web app.

Blazor might not be a good fit if:

  • You need to fully optimize download size and load time of client-side assets.
  • You need to integrate heavily with a different frontend framework ecosystem.
  • You need to support older web browsers that don’t support the modern web platform.

red hat certified specialist in deployment and systems management malaysia

How Blazor works

Blazor provides many features to help you get started and deliver your next web app project fast. Let’s take a tour of the core capabilities of Blazor to help you decide whether you should use Blazor for your next great web app.

Blazor components

Blazor apps are built from components. A Blazor component is a reusable piece of web UI. A Blazor component encapsulates both its rendering and UI event handling logic. Blazor includes various built-in components for form handling, user input validation, displaying large data sets, authentication, and authorization. Developers can also build and share their own custom components, and many prebuilt Blazor components are available from the Blazor ecosystem.

Use standard web technologies

You author Blazor components using Razor syntax, a convenient mixture of HTML, CSS, and C#. A Razor file contains plain HTML and then C# to define any rendering logic, like for conditionals, control flow, and expression evaluation. Razor files are then compiled into C# classes that encapsulate the component’s rendering logic. Because Blazor components authored in Razor are just C# classes, you can call arbitrary .NET code from your components.

UI event handling and data binding

Interactive Blazor components can handle standard web UI interactions using C# event handlers. Components can update their state in response to UI events and adjust their rendering accordingly. Blazor also includes support for two-way data binding to UI elements as a way to keep component state in sync with UI elements.

The following example is a simple Blazor counter component implemented in Razor. Most of the content is HTML, while the @code block contains C#. Every time the button is pressed the IncrementCount C# method is invoked, which increments the currentCount field, and then the component renders the updated value:

razorCopy

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}

Server and client-side rendering

Blazor supports both server and client-side rendering of components to handle various web UI architectures. Components rendered from the server can access server resources, like databases and backend services. By default, Blazor components are rendered statically from the server, generating HTML in response to requests.

You can also configure server components to be interactive, so they can handle arbitrary UI events, maintain state across interactions, and render updates dynamically. Interactive server components handle UI interactions and updates over a WebSocket connection with the browser.

Diagram of Blazor interactive server rendering.

Alternatively, Blazor components can be rendered interactively from the client. The component is downloaded to the client and run from the browser via WebAssembly. Interactive WebAssembly components can access client resources through the web platform, like local storage and hardware, and can even function offline once downloaded.

Diagram of Blazor interactive WebAssembly rendering.

You can choose to render different components from the server or the client within the same app. Many of the pages in your app might not require any interactivity at all, and can be rendered statically from the server. While other more interactive parts of your app can be handled from the server or client. You can decide which component render mode to use at design time or runtime. With Blazor, you have the flexibility to build the web app architecture that’s right for your scenario.

Using Blazor to build a pizza shop

The UI of the pizza shop app breaks down into many reusable components: a page layout with a navbar, individual pages, a pizza catalog and editor, an order component, and so on. Blazor provides built-in support for many of these components, like components for forms and validation. Many of the pages in the app can be handled from the server using static server-side rendering so that the site is mostly stateless and ready to scale. Where more interactivity is needed, the components are made interactive by applying an interactive render mode. To offload work from the server, interactive components are rendered on the client via WebAssembly. By building the entire app with a single web development stack, the app comes together quickly and soon the pizza orders are flowing in.

red hat certified specialist in red hat enterprise linux diagnostics and troubleshooting malaysia

What is Blazor?

Blazor is a modern frontend web framework based on HTML, CSS, and C# that helps you build web apps faster. With Blazor, you build web apps using reusable components that can be run from both the client and the server so that you can deliver great web experiences. Blazor is part of .NET, a developer platform for building anything. .NET is free, open-source, and runs cross-platform.

Some of the benefits of using Blazor include:

  • Build web UI fast with reusable components: Blazor’s flexible component model makes it easy to build reusable components that you can use to assemble apps quickly.
  • Add rich interactivity in C#: Handle arbitrary UI events from the browser and implement component logic all in C#, a modern type-safe language that is easy to learn and highly versatile.
  • One development stack: Build your entire web app from the frontend to the backend using a single development stack and share code for common logic on the client and server.
  • Efficient diff-based rendering: As components render, Blazor carefully tracks what parts of the DOM changed, so that UI updates are fast and efficient.
  • Server and client-side rendering: Render components from both the server and the client to implement various web app architectures and deliver the best possible web app experience.
  • Progressively enhanced server rendering: Use built-in support for enhanced navigation & form handling and streaming rendering to progressively enhance the user experience of server rendered web apps.
  • Interop with JavaScript: Use the ecosystem of JavaScript libraries and browser APIs from your C# code.
  • Integrate with existing apps: Integrate Blazor components with an existing MVC, Razor Pages, or JavaScript based apps.
  • Great tooling: Use Visual Studio or Visual Studio Code to get started in seconds and stay productive with great code editing support.
  • Web, mobile, and desktop: Blazor components can also be used to build native mobile & desktop apps using a hybrid of native and web, called Blazor Hybrid.

red hat certified specialist in linux performance tuning malaysia

Introduction

Building web apps can be a complex effort. Choosing the right web framework for your web development project is an important first step. Blazor is a complete frontend web framework based on the solid foundation of .NET that makes building web apps easier and more productive.

In this module you’ll learn what Blazor is and how its flexible component model makes it easy to build web apps that are fast and richly interactive.

Scenario

Imagine you’re preparing to launch a new web app for your pizza shop that allows customers to easily select from the collection of fresh pizza specials and then customize their pizza order. Customers should have a clear path to place their order and track their pizza delivery. You want to select a web framework for building your web app that helps with building a great user experience for your customers.

Screenshot of pizza shop website built with Blazor.

red hat certified specialist in server hardening malaysia

Build web apps with Blazor

At a glance

  • Level
  • SkillDevelop web apps with Blazor
  • Product
  • Role

Learn how to build your first web app with the Blazor web user-interface framework.

Prerequisites

None

red hat enterprise linux rhel training courses malaysia

When to use ASP.NET Core

ASP.NET Core is a cross-platform, high-performance framework for building modern web applications. Whether ASP.NET Core is the right web development framework for you depends on many factors.

When to use ASP.NET Core

ASP.NET Core for web development is ideal when your web app has any of these requirements:

  • Rich user interfaces: You want to build interactive and dynamic web applications. With support for Blazor and popular front-end JavaScript frameworks, ASP.NET Core allows you to create rich user interfaces.
  • API development: You need to develop robust API services. ASP.NET Core supports both RESTful APIs and gRPC, providing flexibility for different communication needs.
  • Microservices architecture: You’re building a microservices-based architecture. ASP.NET Core’s lightweight and modular design is well-suited for microservices.
  • High performance: Your application demands high performance and scalability. ASP.NET Core is designed to handle high traffic and large-scale applications efficiently.
  • Modern development practices: You prefer modern development practices such as dependency injection, asynchronous programming, and modular architecture. ASP.NET Core supports these practices out of the box.
  • Cross-platform requirements: You need to develop applications that run on Windows, macOS, Linux and Docker. ASP.NET Core’s cross-platform capabilities make it an excellent choice for diverse environments.
  • Cloud integration: You plan to deploy your applications to the cloud. ASP.NET Core integrates seamlessly with Azure and other cloud platforms, simplifying deployment and management.
  • Security and compliance: You require strong security features and compliance with industry standards. ASP.NET Core provides built-in support for HTTPS, data protection, and other security best practices.

When ASP.NET Core might not be a good fit

ASP.NET Core might not be a good fit for your web development needs when your web app has any of these requirements:

  • Minimal requirements: Your application is a simple static page site.
  • Specific language preferences: Your team prefers working with languages other than C#. While ASP.NET Core supports multiple languages, it’s primarily designed for C# development.

red hat linux administration training courses malaysia

How ASP.NET Core works

An ASP.NET Core app is essentially a .NET app with a Program.cs file that sets up the web app component features you need and gets it running.

The most basic ASP.NET Core app’s Program.cs file:

C#Copy

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

With the previous code:

  • A basic ASP.NET Core web application is set up that listens for HTTP GET requests at the root URL (“/”) and responds with “Hello World!”.
  • The app is initialized, configures a single route, and starts the web server.

Blazor

You can build interactive web UI with ASP.NET Core using Blazor. Blazor is a component-based web UI framework integrated with ASP.NET Core, used for building interactive web UIs using HTML, CSS, and C#.

A reusable Blazor component, such as the following Counter component is defined in a Counter.razor file:

razorCopy

@page "/counter"
@rendermode InteractiveServer

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}

With the previous code:

  • A component is created that displays a counter.
  • The @code block contains the component’s logic using C#, including a method to increment the counter.
  • The counter value is displayed and updated each time the button is clicked.
  • A component approach allows for code reuse across different parts of the application and has the flexibility to be run either in the browser or on the server in a Blazor app.

The Counter component can be added to any web page in the app by adding the <Counter /> element.

razorCopy

@page "/"

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

<Counter />

APIs

ASP.NET Core provides frameworks for building APIs, gRPC services, and real-time apps with SignalR to instantly push data updates to clients.

Basic Minimal API:

C#Copy

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/hello", () => "Hello, World!");

app.Run();

With the previous code:

  • A minimal API is set up that listens for HTTP GET requests at the /hello URL and responds with “Hello, World!”.
  • The WebApplicationBuilder is used to configure the app.
  • The MapGet method defines a route and a handler for GET requests.

Middleware

ASP.NET Core uses a pipeline of middleware components to handle HTTP requests and responses. This modular approach provides flexibility, allowing you to customize and extend your application’s functionality by adding or removing middleware components as needed.

The middleware pipeline processes HTTP requests in a sequential manner, ensuring that each component can perform its designated task before passing the request to the next component in the pipeline.

Adding built-in middleware in the Program.cs file:

C#Copy

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseHttpsRedirection();

app.UseRouting();

app.MapStaticAssets();

app.UseAuthentication();

app.UseAuthorization();

app.MapGet("/", () => "Hello World!");

app.Run();

In the previous code, several common middleware components were added:

  • UseHttpsRedirection: Redirects HTTP requests to HTTPS.
  • UseRouting: Enables routing to map requests to endpoints.
  • MapStaticAssets: Optimizes the delivery of static files such as HTML, CSS, JavaScript, images and other assets.
  • UseAuthentication: Adds authentication capabilities.
  • UseAuthorization: Adds authorization capabilities.
  • app.MapGet: This is a simple endpoint to demonstrate that the application is running.

Dependency Injection

ASP.NET Core includes built-in support for dependency injection (DI) for configuring services that are used by the app and its various framework components.

For example, you might want to centrally configure a service using a framework like EntityFramework Core that other parts of your app depend on to access a database. You can configure a database context from EntityFramework Core as a service using dependency injection like this:

C#Copy

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }
    
    public DbSet<Product> Products { get; set; } = default!;
}

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<MyDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

var app = builder.Build();

app.Run();

With the previous code:

  • DbContext is configured as a service using dependency injection.
  • The WebApplicationBuilder is used to configure the app.
  • The AddDbContext method registers the DbContext with the dependency injection container.
  • The connection string is retrieved from the configuration and used to set up the database context.

Configuration

ASP.NET Core supports accessing configuration data from a variety of sources, like JSON files, environment variables, and command-line arguments.

Configuring a connection string in an appsetting.json file:

JSONCopy

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;"
  }
}

In the Program.cs file:

C#Copy

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<MyDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

var app = builder.Build();

app.Run();

With the previous code:

  • The connection string is configured in the appsettings.json file.
  • The WebApplicationBuilder is used to configure the app.
  • The AddDbContext method registers the DbContext with the dependency injection container.
  • The connection string is retrieved from the configuration and used to set up the database context.

Monitoring and diagnostics

ASP.NET Core provides a comprehensive suite of tools for monitoring and maintaining the health and performance of your applications. These features can be easily added to your application as middleware components, integrating specific functionalities into your project:

  • Built-in metrics: ASP.NET Core includes built-in metrics that track various aspects of your application’s performance, such as request rates, response times, and error rates.
  • Flexible logging framework: A flexible logging framework is built in, and supports various logging providers, including console, debug, and event source. This helps in capturing detailed logs for diagnostics and monitoring.
  • Tracing: ASP.NET Core supports distributed tracing, which helps you track the flow of requests across different services and components. This is useful for diagnosing performance issues and understanding the interactions between different parts of your application.
  • OpenTelemetry: ASP.NET Core integrates with OpenTelemetry, an open-source observability framework for cloud-native software. OpenTelemetry provides standardized APIs and instrumentation for collecting metrics, logs, and traces, enabling you to monitor and diagnose your applications more effectively.
  • Health Checks: The health checks API allows you to monitor the health of your application and its dependencies. You can configure health checks to report the status of various components, such as databases, external services, and more.
  • Diagnostics Tools: ASP.NET Core provides various diagnostic tools, such as dotnet-trace, dotnet-dump, and dotnet-gcdump, which help you collect and analyze diagnostic data from your application.

red hat linux certification malaysia

What is ASP.NET Core?

ASP.NET Core is a cross-platform, high-performance framework for building modern web applications. This open-source framework allows developers to create web applications, services, and APIs that can run on Windows, macOS, and Linux. It is built for large-scale app development and can handle any size workload, making it a robust choice for enterprise-level applications.

Full stack web development

ASP.NET Core is a full stack web framework that seamlessly integrates front-end and back-end development needs within a single consistent framework:

  • For front-end development, ASP.NET Core includes Blazor, a component-based web UI framework based on C# that supports both server-side rendering and client-side rendering via WebAssembly.
  • Alternatively, ASP.NET Core can be integrated with JavaScript front-end frameworks like Angular, React, and Vue.

API development

ASP.NET Core is a powerful framework for API development:

  • It supports creating JSON-based APIs, gRPC services, and real-time services using SignalR.
  • With built-in OpenAPI support, developers can easily generate and visualize API documentation, simplifying the design and consumption of APIs.
  • You can use ASP.NET Core to build back-end APIs for a variety of apps, including web apps and native mobile apps.

Modular architecture

ASP.NET Core’s modular architecture offers a flexible approach to modern web development:

  • This architecture includes support for dependency injection, middleware, configuration, and logging.
  • Middleware components can be configured to handle requests and responses, including built-in middleware for authentication, routing, session management, and static file serving.
  • The dependency injection design pattern enhances testability and maintainability.

Security built-in

ASP.NET Core helps you build secure applications thanks to its robust built-in security features for authentication and authorization. These features help applications manage user identities and protect sensitive data effectively.

Increased productivity

Overall, ASP.NET Core provides a productive development experience, enabling developers to build high-quality full stack web apps efficiently and effectively.

sap erp procurement material management training courses malaysia

Scenario

Imagine you and your team are asked to create a web app for an online store. Your team might be expected to provide any number of the following modern web app features:

  • Customer browsing and search options to navigate a wide selection of goods.
  • Authentication, authorization, profile management, and order tracking.
  • Secure customer payment interaction for purchases.
  • Real-time interactive chat with the store’s customer service team.
  • App logging and health monitoring.
  • Cloud-ready, environment-based configuration.

ASP.NET Core provides the tools and libraries needed to implement these features and more, efficiently and seamlessly, ensuring a high-quality user experience and robust application performance.

What is the main goal?

By the end of this session, you’ll know:

  • What ASP.NET Core features will help you successfully meet modern web app demands.
  • An overview of how ASP.NET Core works.
  • When to use ASP.NET Core.

sap erp pp production planning training courses malaysia

Understand ASP.NET Core fundamentals

At a glance

  • Level
  • Product
  • Role
  • Subject

Learn the fundamentals of building web applications with ASP.NET Core. This learning path teaches the basics required for front-end and back-end development with ASP.NET Core.

Prerequisites

  • Experience building web applications using .NET and C#

sap fico financial accounting training courses malaysia