푸터 콘텐츠로 바로가기
.NET 도움말

What is Blazor Framework (How it Works for Developers Tutorial)

Blazor is an ASP.NET Framework launched by Microsoft back in 2018. The launch of the Blazor framework was advantageous as it allowed developers to create Single Page Web Applications using C# instead of JavaScript.

Blazor lets you build interactive web UIs using C# that runs in the browser with WebAssembly (abbreviated as Wasm). Blazor apps are composed of reusable web UI components implemented using C#, HTML, and CSS. Both client and server code is written in C#, allowing you to share code and libraries.

Blazor can run your client-side C# code directly in the browser using WebAssembly. Because it's .NET running on WebAssembly, you can reuse code and libraries from server-side parts of your application.

Alternatively, Blazor can run your client logic on the server. Client UI events are sent back to the server using SignalR, a real-time messaging framework. Once execution completes, the required UI changes are sent to the client and merged into the Document Object Model (DOM).

What is WebAssembly?

Blazor WebAssembly is a Single-Page App (SPA) framework for building interactive client-side web apps with .NET. Blazor WebAssembly uses open web standards that allow development without plugins or recompiling code into other languages. Blazor WebAssembly works in all modern web browsers.

Running .NET code inside web browsers is made possible by WebAssembly. WebAssembly is a compact bytecode format optimized for fast download and maximum execution speeds. WebAssembly is an open web standard and is supported in web browsers without plugins.

WebAssembly code can access the full functionality of the browser via JavaScript. Known as JavaScript Interoperability, it is often shortened to JavaScript interop or JS interop. .NET code executed via WebAssembly runs in the browser's JavaScript sandbox with the protections that the sandbox provides against malicious actions on the client machine.

Build Native Apps

We can build native client apps using existing Blazor Web UI components with Blazor Hybrid. Blazor components can be shared across mobile, desktop, and web while taking advantage of full access to native client capabilities. We can use Blazor Hybrid to build cross-platform apps with .NET Multi-platform App UI (MAUI), or to modernize existing Windows Presentation Foundation (WPF) and Windows Forms apps.

In a Blazor Hybrid app, Razor components run natively on the device. Components render to an embedded Web View control through a local interop channel. Components don't run in the browser, and WebAssembly isn't involved. Razor components load and execute code quickly, and components have full access to the native capabilities of the device through the .NET platform.

Let's create a demo application to better understand how Blazor apps work.

Create a Blazor Server Application

To create our first Blazor app, we need to create a new Visual Studio project.

  • Open Visual Studio.
  • Click on the Create New Project button.
  • Select Blazor Server App Template.
  • Click on the Next button.
  • Name your Application.
  • Click on the Next button.
  • Select a target Framework.
  • Click on the Create Project button.

A New Project will be created as shown below.

What is Blazor and How Does It Work - Figure 1

Several files were created to give you a simple Blazor app that is ready to run.

  • Program.cs is the entry point for the app that starts the server and where you configure the app services and middleware.
  • App.razor is the root component of the app.
  • The Pages directory contains some example web pages for the app.
  • The launchSettings.json file inside the Properties directory defines different profile settings for the local development environment. A port number is automatically assigned at project creation and saved to this file.

Run this template app.

Running the Blazor App

There are three Blazor components automatically created in the template.

Home Component

What is Blazor and How Does It Work - Figure 2

Click on Counter on the side menu. You will see that clicking the button increments the counter without changing or reloading the page. Incrementing the counter dynamically in a web application normally requires JavaScript, but with Blazor, we can achieve this using C#. This is the reason that ASP.NET developers like Blazor so much. It helps .NET developers build web apps quickly and easily.

Counter Component

What is Blazor and How Does It Work - Figure 3

We can see the code of the Counter component in the Counter.razor file located inside the Pages folder of our solution.

@page "/counter"
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
    private int currentCount = 0;

    // This method increments the counter value when the button is clicked
    private void IncrementCount()
    {
        currentCount++;
    }
}

A request for /counter in the browser, as specified by the @page directive at the top, causes the Counter component to render its content.

Each time the Click me button is selected:

  • The onclick event is executed.
  • The IncrementCount method is called.
  • The currentCount is incremented.
  • The component is rendered to show the updated count.

Each of the .razor files defines a UI component that can be reused.

Open the Index.razor file in Visual Studio. The Index.razor file already exists because it was created when you created the project. It's located in the Pages folder inside the BlazorApp directory that was created earlier.

Fetch Component

There is another component named "Fetch Component". This component also injects a service used for backend server-side development. Let's replace this code to generate a PDF from a URL to better understand the power of Blazor web development.

Generate PDF from URL

First of all, we need to install a third-party library for generating PDF files. The library we will use is IronPDF - PDF Generation for .NET. It's easy to use, includes many features, and is free for development. You can learn more about using IronPDF in your Blazor App by reading the IronPDF Blazor Documentation.

Install IronPDF NuGet Package

We can also install the IronPDF NuGet package in the Blazor WebAssembly app similar to the normal ASP.NET Core application.

Open NuGet Package Manager Console, and write the following command:

Install-Package IronPdf

The library will be installed as shown below.

What is Blazor and How Does It Work - Figure 4

Remove all the existing code from FetchData.razor file and add the following code sample:

@page "/fetchdata"

@using myBlazorAPP.Data
@inject WeatherForecastService ForecastService

<h1>Generate PDF FROM URL</h1>
<p>This component demonstrates generating PDF from URL using IronPDF in Blazor Application</p>
<input type="text" @bind="URL" placeholder="URL HERE..."/>
<button @onclick="GeneratePDF">Generate PDF</button>

@code {
    private string URL { get; set; }

    // This method calls the service to generate a PDF document from a given URL
    protected async Task GeneratePDF()
    {
        await ForecastService.GeneratePDFfromURL(URL);
    }
}

Above is the client-side Blazor code for generating PDF files. It defines one button and one input box. The input field is bound to the URL variable.

Now, let's write server-side code for our app.

Open WeatherForecastService.cs file and replace all the existing code with the following code snippet:

using System;
using System.Threading.Tasks;
using IronPdf;

namespace myBlazorAPP.Data
{
    public class WeatherForecastService
    {
        // This method generates a PDF file asynchronously from a provided URL
        public async Task GeneratePDFfromURL(string URL)
        {
            ChromePdfRenderer renderer = new ChromePdfRenderer();
            var pdfDoc = await renderer.RenderUrlAsPdfAsync(URL);
            pdfDoc.SaveAs(@"myFile.pdf");
        }
    }
}
using System;
using System.Threading.Tasks;
using IronPdf;

namespace myBlazorAPP.Data
{
    public class WeatherForecastService
    {
        // This method generates a PDF file asynchronously from a provided URL
        public async Task GeneratePDFfromURL(string URL)
        {
            ChromePdfRenderer renderer = new ChromePdfRenderer();
            var pdfDoc = await renderer.RenderUrlAsPdfAsync(URL);
            pdfDoc.SaveAs(@"myFile.pdf");
        }
    }
}
$vbLabelText   $csharpLabel

Let's run our application to see the output.

What is Blazor and How Does It Work - Figure 5

Paste a URL in the input box and click on Generate PDF. The PDF file will be generated and the file can be seen in the app folder.

Open the PDF file as shown below.

What is Blazor and How Does It Work - Figure 6

We have generated a PDF from the URL with just three lines of code. This is the power of IronPDF.

IronPDF is provided by Iron Software and it is part of Iron Software's Iron Suite Products. You can save money and purchase five products for the cost of purchasing two of them by acquiring the full Iron Suite.

Summary

Blazor is a framework for building interactive client-side web UI with Microsoft's .NET Framework.

  • Create rich interactive UIs using C# instead of JavaScript.
  • Share server-side and client-side app logic written in .NET.
  • Render the UI as HTML and CSS for wide browser support, including mobile browsers.
  • Integrate with modern hosting platforms, such as Docker.
  • Build hybrid desktop and mobile apps with .NET and Blazor.

Using .NET for client-side web development offers the following advantages:

  • Write code in C# instead of JavaScript.
  • Leverage the existing .NET ecosystem of .NET libraries.
  • Share app logic across server and client.
  • Benefit from .NET's performance, reliability, and security.
  • Stay productive on Windows, Linux, or macOS with a development environment, such as Visual Studio or Visual Studio Code.
  • Build on a common set of languages, frameworks, and tools that are stable, feature-rich, and easy to use.

자주 묻는 질문

C#을 사용하여 URL에서 PDF를 생성하려면 어떻게 해야 하나요?

IronPDF 라이브러리를 사용하여 C#의 URL에서 PDF를 생성할 수 있습니다. 여기에는 URL을 PDF 문서로 렌더링하기 위해 ChromePdfRenderer 클래스를 활용하는 것이 포함됩니다.

웹 개발에 Blazor를 사용하면 어떤 주요 이점이 있나요?

Blazor를 사용하면 개발자가 C#으로 웹 애플리케이션을 구축할 수 있으므로 클라이언트와 서버 간에 코드를 공유할 수 있습니다. 또한 기존 .NET 에코시스템을 사용하고 WebAssembly를 통해 최신 브라우저를 지원하여 성능과 생산성을 향상시킵니다.

기본 디바이스 기능을 통합하는 데 Blazor를 어떻게 사용할 수 있나요?

Blazor는 크로스 플랫폼 애플리케이션을 위해 .NET MAUI와 같은 프레임워크를 활용하여 구성 요소를 기본적으로 실행하고 .NET을 통해 디바이스 기능에 액세스할 수 있는 Blazor Hybrid로 네이티브 애플리케이션을 만드는 데 사용할 수 있습니다.

WebAssembly는 Blazor 애플리케이션을 어떻게 향상시키나요?

WebAssembly는 플러그인 없이도 최신 브라우저에서 .NET 코드를 실행할 수 있도록 지원하여 Blazor 애플리케이션을 향상시킵니다. 이를 통해 전체 브라우저 기능을 위해 JavaScript 상호 운용성을 활용할 수 있는 대화형 클라이언트 측 웹 애플리케이션을 만들 수 있습니다.

Visual Studio에서 Blazor Server 애플리케이션을 만들려면 어떻게 해야 하나요?

Visual Studio에서 Blazor Server 애플리케이션을 만들려면 새 프로젝트를 시작하고, Blazor Server 앱 템플릿을 선택하고, 프로젝트 이름을 지정하고, 대상 프레임워크를 선택한 다음 프로젝트 생성을 진행해야 합니다. 이 프로세스는 Blazor Server 앱에 필요한 구조를 설정합니다.

Blazor의 JavaScript 상호 운용성이란 무엇인가요?

JavaScript 상호 운용성 또는 JS 인터롭은 브라우저에서 실행되는 .NET 코드가 JavaScript와 상호 작용할 수 있도록 하여 Blazor 애플리케이션 내에서 전체 브라우저 기능을 사용할 수 있도록 하는 Blazor의 기능입니다.

블레이저 애플리케이션을 Docker를 사용하여 배포할 수 있나요?

예, Blazor 애플리케이션은 다양한 서버 환경에서 애플리케이션을 보다 쉽게 관리하고 배포할 수 있는 Docker를 사용하여 배포할 수 있으므로 확장성과 최신 호스팅 플랫폼과의 통합이 향상됩니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.