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

.NET Aspire (How it Works For Developers)

.NET Aspire stands as a decisive, cloud-ready stack framework tailored for constructing observable, production-ready, distributed applications. Delivered through a set of NuGet packages, Aspire efficiently addresses various cloud-native service discovery considerations and aims to provide consistent setup patterns. In the realm of .NET cloud-native apps, the norm involves smaller, interlinked components or microservices in distributed apps, departing from the traditional monolithic code structure. These applications typically rely on numerous services like databases, messaging systems, cloud resources, and caching.

Distributed applications, in this context, leverage computational resources spanning multiple nodes, such as containers operating on diverse hosts. Effective communication across network boundaries is essential for these nodes to collaboratively deliver responses to end users. Specifically, a cloud-native distributed application, is a distinct category within distributed applications, capitalizing on the scalability, resilience, and manageability inherent in cloud-native app infrastructures.

In this article, we will discuss the .NET Aspire components to create a web application. Also, we will use the IronPDF library to create and download PDF files in the Aspire .NET project component.

1. Introduction to .NET Aspire

.NET Aspire application stands as a purposeful initiative aimed at enhancing the development experience for .NET cloud-native apps within the .NET ecosystem. It introduces a cohesive and opinionated suite of tools and design patterns crafted to facilitate the seamless construction and operation of distributed apps. The core objectives of .NET Aspire starter application encompass:

  1. Orchestration: .NET Aspire orchestration assists features robust capabilities for orchestrating multi-project applications and their intricate dependencies. This functionality ensures smooth execution and seamless connectivity between diverse components of .NET projects.
  2. Components: The components offered by .NET Aspire orchestration are encapsulated within NuGet packages, representing widely utilized services like local Redis container resource or Postgres. These components are characterized by standardized interfaces, guaranteeing consistent and seamless integration with your application. By leveraging these pre-packaged components, developers can expedite the development process and maintain a higher level of interoperability and configurable cloud-native applications using .NET Aspire project templates.
  3. Tooling: .NET Aspire starter templates incorporate a comprehensive set of tools tailored to streamline the development workflow. Project templates and tooling experiences are thoughtfully integrated into Visual Studio and the .NET CLI, empowering developers to create and interact with .NET Aspire apps effortlessly. This inclusive tooling framework enhances productivity and provides a cohesive environment for developing and managing .NET Aspire app configurations and project templates.

In essence, .NET Aspire serves as a holistic solution, addressing key aspects of specific cloud-native concerns such as orchestration, component integration, and tooling, all aimed at elevating the efficiency and consistency of building and deploying .NET cloud-native applications.

2. Getting Started with .NET Aspire

Before engaging with .NET Aspire, ensure that the following components are locally installed:

  1. .NET 8.0: Make sure to have .NET 8.0 installed on your system.
  2. .NET Aspire Workload: Acquire the .NET Aspire workload by either utilizing the VS installer or executing the dotnet workload install aspire command.
  3. Integrated Developer Environment (IDE) or Code Editor: Visual Studio 2022 should be installed on the system beforehand.

If all these requirements are met, you are good to go with the development of your first .NET Aspire components that handle apps.

3. Create a New .NET Aspire Project

To create .NET Aspire apps, follow the following steps.

  1. Open Visual Studio and click on Create a new project.
  2. A new window will appear. In this new window, search Aspire on the search bar.
  3. A list will appear below, from that list select the Aspire Starter apphost project and package references and click on Next.
  4. A new window will appear. In this new window write the project name and click on Next.
  5. In this window select the target framework and click on the Create button.

The .NET Aspire application will be created in a few seconds, and you will be good to get started with the development and customization.

4. Running and Testing the .NET Aspire application

Once the project is created just click on the Run button, it will take some time to create a build and after that, it will open a web page of our Aspire web application Home page.

This home page will contain our .NET Aspire Cloud-native apps stack for building observable production-ready .NET Aspire starter applications.

.NET Aspire (How it Works For Developers): Figure 1 - Aspire Home Page

Now click on the links to interact with .NET. For now click on the .NET Aspire web frontend project and package references. It will open the new webpage with a different port name.

.NET Aspire (How it Works For Developers): Figure 2 - New Webpage

5. Introducing IronPDF C#

IronPDF documentation describes it as a powerful and versatile C# library that empowers developers to effortlessly integrate advanced PDF generation and manipulation capabilities into their applications. Developed by Iron Software, this feature-rich library offers a comprehensive set of tools for creating, modifying, and rendering PDF documents directly within C# applications.

With IronPDF, developers can seamlessly generate PDFs from various sources, such as HTML, images, and existing documents, while maintaining precise control over formatting and layout. Whether it's creating dynamic reports, converting HTML content to PDF, or adding annotations to existing documents, IronPDF streamlines the PDF handling process, making it an invaluable asset for C# developers seeking a reliable and efficient solution for their document management needs.

5.1. Installing IronPDF

To seamlessly install IronPDF, leverage the NuGet Package Manager within Visual Studio. The designated package for installation is titled IronPDF. Simply copy and paste the following command into the Package Manager Console and hit enter:

Install-Package IronPdf

5.2. Integrating IronPDF with Aspire Component

Integrating IronPDF with the Aspire component is the same as integrating with the Blazor web application because the Aspire components can use the Blazor application as a component. In this code example, we will change the code of the Counter Page to create and download a PDF file.

Open the counter.razor file and replace the code with the below code.

@page "/PrintPDF"
@rendermode InteractiveServer
@using IronPdf
<PageTitle>Print PDF</PageTitle>
<h1>IronPDF</h1>
<p role="status">Click on the button below to create and download the PDF file </p>
<button class="btn btn-primary" @onclick="IncrementCount">Print</button>
@code {
    private int currentCount = 0;

    /// <summary>
    /// Handles the click event of the "Print" button.
    /// This function will generate a PDF from an HTML string and prompt the user to download it.
    /// </summary>
    private void IncrementCount()
    {
        var renderer = new ChromePdfRenderer();
        // Create a PDF from an HTML string using C#
        var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
        // Export to a file using JavaScript Interop to initiate download
        JSRuntime.InvokeVoidAsync("saveAsFile", "output.pdf", Convert.ToBase64String(pdf.Stream.ToArray()));
    }
}
@page "/PrintPDF"
@rendermode InteractiveServer
@using IronPdf
<PageTitle>Print PDF</PageTitle>
<h1>IronPDF</h1>
<p role="status">Click on the button below to create and download the PDF file </p>
<button class="btn btn-primary" @onclick="IncrementCount">Print</button>
@code {
    private int currentCount = 0;

    /// <summary>
    /// Handles the click event of the "Print" button.
    /// This function will generate a PDF from an HTML string and prompt the user to download it.
    /// </summary>
    private void IncrementCount()
    {
        var renderer = new ChromePdfRenderer();
        // Create a PDF from an HTML string using C#
        var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
        // Export to a file using JavaScript Interop to initiate download
        JSRuntime.InvokeVoidAsync("saveAsFile", "output.pdf", Convert.ToBase64String(pdf.Stream.ToArray()));
    }
}
$vbLabelText   $csharpLabel

After that write the JavaScript code to download the PDF File. Write this code in the script tag in the scope of the HTML body tag. Below is the code to add to your project.

<script type="text/javascript">
    function saveAsFile(filename, bytesBase64) {
        if (navigator.msSaveBlob) {
            //Download document in Edge browser
            var data = window.atob(bytesBase64);
            var bytes = new Uint8Array(data.length);
            for (var i = 0; i < data.length; i++) {
                bytes[i] = data.charCodeAt(i);
            }
            var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
            navigator.msSaveBlob(blob, filename);
            window.navigator.msSaveOrOpenBlob(blob);
        }
        else {
            var link = document.createElement('a');
            link.download = filename;
            link.href = "data:application/octet-stream;base64," + bytesBase64;
            document.body.appendChild(link); // Needed for Firefox
            link.click();
            document.body.removeChild(link);
        }
    }
</script>
<script type="text/javascript">
    function saveAsFile(filename, bytesBase64) {
        if (navigator.msSaveBlob) {
            //Download document in Edge browser
            var data = window.atob(bytesBase64);
            var bytes = new Uint8Array(data.length);
            for (var i = 0; i < data.length; i++) {
                bytes[i] = data.charCodeAt(i);
            }
            var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
            navigator.msSaveBlob(blob, filename);
            window.navigator.msSaveOrOpenBlob(blob);
        }
        else {
            var link = document.createElement('a');
            link.download = filename;
            link.href = "data:application/octet-stream;base64," + bytesBase64;
            document.body.appendChild(link); // Needed for Firefox
            link.click();
            document.body.removeChild(link);
        }
    }
</script>
JAVASCRIPT

Just run the code after that it will look something like the below image.

.NET Aspire (How it Works For Developers): Figure 3 - Blazor

To create and download a PDF file click on the Print button. It will create and download the PDF file named output.pdf file.

.NET Aspire (How it Works For Developers): Figure 4 - PDF Download

6. Conclusion

.NET Aspire emerges as a pivotal framework, purposefully designed to develop robust, observable, and distributed applications in the cloud environment. By providing a cohesive set of tools and design patterns, .NET Aspire simplifies the complexities associated with building cloud-native applications, offering seamless orchestration, component integration, and a user-friendly tooling framework. With a focus on scalability, resilience, and manageability, .NET Aspire aligns with the paradigm shift towards microservices and distributed architectures.

As developers embark on their journey with .NET Aspire, they gain access to a comprehensive suite of features, from orchestrated multi-project applications to standardized components encapsulated in NuGet packages. By adhering to the prerequisites and following the straightforward steps outlined in the guide, developers can effortlessly create, run, and test .NET Aspire applications.

Furthermore, the integration of IronPDF into Aspire components showcases the extensibility and versatility of the framework, enabling developers to seamlessly incorporate advanced PDF generation and manipulation capabilities into their cloud-native applications. Overall, .NET Aspire, with its well-defined objectives and user-friendly approach, positions itself as a valuable asset for developers seeking an efficient and consistent solution for building and deploying cloud-native applications within the .NET ecosystem.

For a complete tutorial on using IronPDF with Blazor web applications visit IronPDF's blog tutorial. To get a free trial of IronPDF, visit the IronPDF licensing page to get your free trial license.

자주 묻는 질문

C#에서 HTML을 PDF로 변환하려면 어떻게 해야 하나요?

IronPDF의 RenderHtmlAsPdf 메서드를 사용하여 HTML 문자열을 PDF로 변환할 수 있습니다. 또한 RenderHtmlFileAsPdf를 사용하여 HTML 파일을 PDF로 변환할 수도 있습니다.

클라우드 네이티브 애플리케이션 개발에서 .NET Aspire의 목적은 무엇인가요?

.NET Aspire는 개발자가 관찰 가능하고 프로덕션에 바로 사용할 수 있는 분산 애플리케이션을 구축할 수 있도록 설계되었습니다. 이 도구는 오케스트레이션 도구, 구성 요소 통합 및 클라우드 네이티브 애플리케이션에서 마이크로서비스 아키텍처를 관리하기 위한 포괄적인 도구 세트를 제공합니다.

IronPDF는 .NET Aspire 프로젝트와 어떻게 통합되나요?

IronPDF는 .NET Aspire 프로젝트에 통합하여 고급 PDF 생성 및 조작 기능을 제공할 수 있습니다. 이를 통해 개발자는 클라우드 네이티브 애플리케이션 내에서 PDF를 원활하게 생성하고 관리할 수 있습니다.

웹 애플리케이션에서 IronPDF의 일반적인 용도는 무엇인가요?

IronPDF는 PDF 보고서 생성, HTML 콘텐츠를 PDF로 변환, 문서 워크플로우 관리를 위해 웹 애플리케이션에서 자주 사용됩니다. 개발자에게 .NET 애플리케이션 내에서 PDF 작업을 처리할 수 있는 강력한 도구 세트를 제공합니다.

.NET 프로젝트에서 IronPDF를 사용할 때 문제를 해결하려면 어떻게 해야 하나요?

IronPDF 문제를 해결하려면 NuGet 패키지가 올바르게 설치되어 있고 모든 종속성이 올바르게 참조되고 있는지 확인하세요. 콘솔에서 오류 메시지를 확인하고 추가 지침은 IronPDF 설명서 또는 지원팀에 문의하세요.

.NET Aspire 프레임워크의 주요 구성 요소는 무엇인가요?

.NET Aspire에는 클라우드 네이티브 애플리케이션의 개발 및 관리를 간소화하도록 설계된 오케스트레이션 기능, 빠른 개발을 위한 사전 패키지 구성 요소, Visual Studio 및 .NET CLI 내의 통합 도구가 포함되어 있습니다.

마이크로서비스 아키텍처에서 .NET Aspire는 어떤 이점을 제공하나요?

.NET Aspire는 일관된 설정 패턴, 강력한 오케스트레이션, 구성 요소의 원활한 통합을 제공하여 클라우드 네이티브 환경에서 마이크로서비스 아키텍처를 더 쉽게 관리하고 배포할 수 있도록 합니다.

.NET 애플리케이션에서 IronPDF를 사용하는 방법에 대한 자세한 내용은 어디에서 확인할 수 있나요?

.NET 애플리케이션과 함께 IronPDF를 사용하는 방법에 대해 자세히 알아보려면 IronPDF 블로그와 문서에서 튜토리얼과 예제를 확인하세요. 이러한 리소스는 IronPDF를 효과적으로 통합하고 사용하는 방법에 대한 자세한 지침을 제공합니다.

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

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

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