C#에서 IronPDF와 함께 플루언트 검증을 사용하는 방법
Fluent Validation이란 무엇인가요?
FluentValidation은 강력한 형식의 검증 규칙을 구축하는 데 도움을 주는 .NET 검증 라이브러리입니다. 유창한 인터페이스와 람다 표현식을 사용하여 코드를 더욱 읽기 쉽고 유지 관리할 수 있게 만듭니다. 모델 클래스에서 데이터 주석이나 수동 검증을 사용하는 대신, Fluent Validation을 사용하여 검증 로직을 위한 별도의 클래스를 구축할 수 있습니다.
Fluent Validation은 검증 게임에 더 많은 유연성을 제공합니다. 일반적인 시나리오에 대한 내장 검증기, 사용자 정의 검증을 구축할 수 있는 기능, 검증 규칙을 연결하는 간단한 방식을 통해 Fluent Validation은 .NET Core 도구 키트의 강력한 도구입니다.
Fluent Validation 이해하기
Fluent Validation은 .NET용 오픈 소스 라이브러리로, 모델 클래스에 대한 검증 규칙을 쉽게 구축할 수 있게 합니다.
- 검증기: 검증기는 검증 논리를 캡슐화한 클래스입니다. 일반적으로
AbstractValidator<t>기본 클래스를 상속하여 생성됩니다. - 규칙: 규칙은 속성이 충족해야 하는 검증 조건입니다. 규칙은 유효성 검사 클래스에서
RuleFor메서드를 사용하여 정의됩니다. - 유효성 검사 실패: 규칙이 실패하면 Fluent Validation은 오류에 대한 세부 정보를 포함하는
ValidationFailure객체를 생성하며, 여기에는 속성 이름과 오류 메시지가 포함됩니다.
IronPDF 란 무엇인가요?
IronPDF - C#에서 HTML을 PDF로 변환하기은 HTML 콘텐츠로부터 PDF 문서를 생성할 수 있게 해주는 강력한 .NET 라이브러리입니다. 청구서, 보고서 또는 기타 문서를 생성해야 하는지에 관계없이, IronPDF는 사용하기 쉬운 솔루션을 제공합니다. ASP.NET Core 응용 프로그램과 매끄럽게 통합되어 몇 줄의 코드로 고품질 PDF 파일을 생성할 수 있습니다.
IronPDF와 함께 Fluent Validation 사용하기
이제 Fluent Validation 및 IronPDF가 무엇인지 이해했으므로, 이들이 어떻게 함께 사용될 수 있는지 살펴봅시다. 이 튜토리얼은 ASP.NET Core에서 FluentValidation을 사용하여 송장 내용을 검증한 후 IronPDF를 사용하여 PDF를 생성하는 송장 생성기를 구축하는 데 도움이 될 것입니다.
프로젝트 설정
시작하기 위해 Visual Studio 또는 선호하는 개발 환경에서 새 콘솔 응용 프로그램을 만듭니다.
- Visual Studio를 열고 파일 > 새로 만들기 > 프로젝트로 이동합니다.
-
프로젝트 템플릿으로 'Console App (ASP.NET Core)'를 선택하고 프로젝트 이름을 지정하세요.
새 콘솔 애플리케이션 생성 -
다음 버튼을 클릭하고 프로젝트 이름과 저장소 위치를 선택하여 구성하세요.
새로운 애플리케이션 구성 -
다음 버튼을 클릭하고 .NET Framework를 선택하세요. 최신 .NET Framework (7)를 권장합니다.
.NET Framework 선택 - 생성 버튼을 클릭하여 프로젝트를 생성하세요.
필수 패키지를 설치하세요
프로젝트가 생성되면 Fluent Validation과 IronPDF에 필요한 NuGet 패키지를 추가하세요.
- Solution Explorer에서 프로젝트를 마우스 오른쪽 버튼으로 클릭하고 'Manage NuGet Packages'를 선택하세요.
-
'FluentValidation'을 검색하고 '설치'를 클릭하여 패키지를 프로젝트에 추가하세요.
NuGet 패키지 관리자 UI에서 FluentValidation Install-Package - 마찬가지로 'IronPDF - 강력한 .NET PDF 라이브러리'를 검색하고 IronPDF 패키지를 설치하세요.
대안으로, NuGet 패키지 관리자 콘솔을 사용하여 다음 명령어로 IronPDF를 설치할 수 있습니다:
Install-Package IronPdf
패키지 관리자 콘솔에서 IronPdf Install-Package
프로젝트와 필요한 Install-Package가 완료되면 PDF 콘텐츠 클래스를 정의합니다.
PDF 콘텐츠 정의
이 예제에서는 두 개의 클래스 InvoiceContent와 InvoiceItem에서 HTML 코드를 사용하여 간단한 송장 PDF를 생성할 것입니다.
using System.Collections.Generic;
using System.Linq;
public abstract class PdfContent
{
// Abstract method to generate the HTML string
public abstract string RenderHtml();
}
public class InvoiceContent : PdfContent
{
public string CustomerName { get; set; }
public string Address { get; set; }
public List<InvoiceItem> InvoiceItems { get; set; }
// Constructs the HTML representation of the invoice
public override string RenderHtml()
{
string invoiceItemsHtml = string.Join("", InvoiceItems.Select(item => $"<li>{item.Description}: {item.Price}</li>"));
return $"<h1>Invoice for {CustomerName}</h1><p>{Address}</p><ul>{invoiceItemsHtml}</ul>";
}
}
public class InvoiceItem
{
public string Description { get; set; }
public decimal Price { get; set; }
}
using System.Collections.Generic;
using System.Linq;
public abstract class PdfContent
{
// Abstract method to generate the HTML string
public abstract string RenderHtml();
}
public class InvoiceContent : PdfContent
{
public string CustomerName { get; set; }
public string Address { get; set; }
public List<InvoiceItem> InvoiceItems { get; set; }
// Constructs the HTML representation of the invoice
public override string RenderHtml()
{
string invoiceItemsHtml = string.Join("", InvoiceItems.Select(item => $"<li>{item.Description}: {item.Price}</li>"));
return $"<h1>Invoice for {CustomerName}</h1><p>{Address}</p><ul>{invoiceItemsHtml}</ul>";
}
}
public class InvoiceItem
{
public string Description { get; set; }
public decimal Price { get; set; }
}
Imports System.Collections.Generic
Imports System.Linq
Public MustInherit Class PdfContent
' Abstract method to generate the HTML string
Public MustOverride Function RenderHtml() As String
End Class
Public Class InvoiceContent
Inherits PdfContent
Public Property CustomerName() As String
Public Property Address() As String
Public Property InvoiceItems() As List(Of InvoiceItem)
' Constructs the HTML representation of the invoice
Public Overrides Function RenderHtml() As String
Dim invoiceItemsHtml As String = String.Join("", InvoiceItems.Select(Function(item) $"<li>{item.Description}: {item.Price}</li>"))
Return $"<h1>Invoice for {CustomerName}</h1><p>{Address}</p><ul>{invoiceItemsHtml}</ul>"
End Function
End Class
Public Class InvoiceItem
Public Property Description() As String
Public Property Price() As Decimal
End Class
위 코드에서는 PdfContent 추상 클래스가 RenderHtml라는 추상 메서드와 함께 정의됩니다. InvoiceContent 클래스는 PdfContent을 확장하여 송장 PDF의 내용을 나타냅니다. 이는 고객의 이름, 주소 및 송장 항목 목록에 대한 속성을 가지고 있습니다. InvoiceItem 클래스는 두 개의 속성, '설명'과 '가격'을 포함하고 있습니다. RenderHtml 메서드는 내용에 기반하여 송장의 HTML 마크업을 생성합니다.
이제 PDF 콘텐츠 정의가 완료되었으니 Fluent Validation을 사용하여 검증 규칙을 생성합니다.
검증 규칙 생성
InvoiceContent 클래스에 대한 유효성 검사 규칙을 작성하려면 InvoiceContentValidator라는 유효성 검사 클래스를 만드십시오. 이 클래스는 FluentValidation에서 제공하는 AbstractValidator<InvoiceContent>을 상속할 것입니다.
using FluentValidation;
public class InvoiceContentValidator : AbstractValidator<InvoiceContent>
{
public InvoiceContentValidator()
{
RuleFor(content => content.CustomerName).NotEmpty().WithMessage("Customer name is required.");
RuleFor(content => content.Address).NotEmpty().WithMessage("Address is required.");
RuleFor(content => content.InvoiceItems).NotEmpty().WithMessage("At least one invoice item is required.");
RuleForEach(content => content.InvoiceItems).SetValidator(new InvoiceItemValidator());
}
}
public class InvoiceItemValidator : AbstractValidator<InvoiceItem>
{
public InvoiceItemValidator()
{
RuleFor(item => item.Description).NotEmpty().WithMessage("Description is required.");
RuleFor(item => item.Price).GreaterThanOrEqualTo(0).WithMessage("Price must be greater than or equal to 0.");
}
}
using FluentValidation;
public class InvoiceContentValidator : AbstractValidator<InvoiceContent>
{
public InvoiceContentValidator()
{
RuleFor(content => content.CustomerName).NotEmpty().WithMessage("Customer name is required.");
RuleFor(content => content.Address).NotEmpty().WithMessage("Address is required.");
RuleFor(content => content.InvoiceItems).NotEmpty().WithMessage("At least one invoice item is required.");
RuleForEach(content => content.InvoiceItems).SetValidator(new InvoiceItemValidator());
}
}
public class InvoiceItemValidator : AbstractValidator<InvoiceItem>
{
public InvoiceItemValidator()
{
RuleFor(item => item.Description).NotEmpty().WithMessage("Description is required.");
RuleFor(item => item.Price).GreaterThanOrEqualTo(0).WithMessage("Price must be greater than or equal to 0.");
}
}
Imports FluentValidation
Public Class InvoiceContentValidator
Inherits AbstractValidator(Of InvoiceContent)
Public Sub New()
RuleFor(Function(content) content.CustomerName).NotEmpty().WithMessage("Customer name is required.")
RuleFor(Function(content) content.Address).NotEmpty().WithMessage("Address is required.")
RuleFor(Function(content) content.InvoiceItems).NotEmpty().WithMessage("At least one invoice item is required.")
RuleForEach(Function(content) content.InvoiceItems).SetValidator(New InvoiceItemValidator())
End Sub
End Class
Public Class InvoiceItemValidator
Inherits AbstractValidator(Of InvoiceItem)
Public Sub New()
RuleFor(Function(item) item.Description).NotEmpty().WithMessage("Description is required.")
RuleFor(Function(item) item.Price).GreaterThanOrEqualTo(0).WithMessage("Price must be greater than or equal to 0.")
End Sub
End Class
소스 코드에서는 InvoiceContentValidator 클래스가 정의되며, 이는 AbstractValidator<InvoiceContent>을 상속합니다. 유효성 검사 클래스의 생성자 내에서 RuleFor 메서드는 InvoiceContent 클래스의 각 속성에 대한 유효성 검사 규칙을 정의합니다.
예를 들어, RuleFor(content => content.CustomerName)는 고객 이름이 비어 있지 않아야 한다는 것을 지정합니다. 마찬가지로 주소와 송장 항목 속성에 대한 검증 규칙을 정의합니다.
RuleForEach 메서드는 InvoiceItems 목록의 각 항목을 반복하고 InvoiceItemValidator을 적용합니다. InvoiceItemValidator 클래스는 InvoiceItem 클래스에 대한 유효성 검사 규칙을 포함합니다.
이러한 검증 규칙이 설정되면 IronPDF를 사용하여 PDF를 생성합니다.
IronPDF를 사용한 PDF 생성
IronPDF - PDF 문서 생성 및 편집은 PDF 문서를 생성하고 조작하는 데 널리 사용되는 .NET 라이브러리입니다. IronPDF는 검증된 인보이스 콘텐츠를 기반으로 PDF를 생성하는 데 사용됩니다.
using IronPdf;
using FluentValidation;
public class PdfService
{
// Generates a PDF document for the provided content
public PdfDocument GeneratePdf<t>(T content) where T : PdfContent
{
// Validate the content using the appropriate validator
var validator = GetValidatorForContent(content);
var validationResult = validator.Validate(content);
// Check if validation is successful
if (!validationResult.IsValid)
{
throw new FluentValidation.ValidationException(validationResult.Errors);
}
// Generate the PDF using IronPDF
var renderer = new ChromePdfRenderer();
return renderer.RenderHtmlAsPdf(content.RenderHtml());
}
// Retrieves the appropriate validator for the content
private IValidator<t> GetValidatorForContent<t>(T content) where T : PdfContent
{
if (content is InvoiceContent)
{
return (IValidator<t>)new InvoiceContentValidator();
}
else
{
throw new NotSupportedException("Unsupported content type.");
}
}
}
using IronPdf;
using FluentValidation;
public class PdfService
{
// Generates a PDF document for the provided content
public PdfDocument GeneratePdf<t>(T content) where T : PdfContent
{
// Validate the content using the appropriate validator
var validator = GetValidatorForContent(content);
var validationResult = validator.Validate(content);
// Check if validation is successful
if (!validationResult.IsValid)
{
throw new FluentValidation.ValidationException(validationResult.Errors);
}
// Generate the PDF using IronPDF
var renderer = new ChromePdfRenderer();
return renderer.RenderHtmlAsPdf(content.RenderHtml());
}
// Retrieves the appropriate validator for the content
private IValidator<t> GetValidatorForContent<t>(T content) where T : PdfContent
{
if (content is InvoiceContent)
{
return (IValidator<t>)new InvoiceContentValidator();
}
else
{
throw new NotSupportedException("Unsupported content type.");
}
}
}
Imports IronPdf
Imports FluentValidation
Public Class PdfService
' Generates a PDF document for the provided content
Public Function GeneratePdf(Of T As PdfContent)(content As T) As PdfDocument
' Validate the content using the appropriate validator
Dim validator = GetValidatorForContent(content)
Dim validationResult = validator.Validate(content)
' Check if validation is successful
If Not validationResult.IsValid Then
Throw New FluentValidation.ValidationException(validationResult.Errors)
End If
' Generate the PDF using IronPDF
Dim renderer = New ChromePdfRenderer()
Return renderer.RenderHtmlAsPdf(content.RenderHtml())
End Function
' Retrieves the appropriate validator for the content
Private Function GetValidatorForContent(Of T As PdfContent)(content As T) As IValidator(Of T)
If TypeOf content Is InvoiceContent Then
Return CType(New InvoiceContentValidator(), IValidator(Of T))
Else
Throw New NotSupportedException("Unsupported content type.")
End If
End Function
End Class
PdfService 클래스는 GeneratePdf 메서드를 제공합니다. 이 메서드는 PdfContent 객체를 입력으로 받아서 유효성 검사된 내용을 바탕으로 PDF 문서를 생성합니다.
먼저, GetValidatorForContent 메서드를 호출하여 내용에 대한 적절한 유효성 검사기를 검색하며, 이는 내용의 타입을 검사하고 해당 유효성 검사기를 반환합니다. 우리의 경우, InvoiceContent을 지원하고 InvoiceContentValidator를 사용합니다.
다음으로, 유효성 검사기의 Validate 메서드를 호출하여 내용을 유효성 검사합니다. 유효성 검사 결과는 ValidationResult 객체에 저장됩니다.
유효성 검사가 실패하면 (!validationResult.IsValid), 유효성 검사 오류와 함께 FluentValidation.ValidationException이 발생합니다. 그렇지 않으면, IronPDF를 사용하여 PDF가 생성됩니다.
ChromePdfRenderer 인스턴스가 HTML 콘텐츠를 PDF로 렌더링하기 위해 생성됩니다. RenderHtmlAsPdf 메서드는 renderer 객체에서 호출되며, HTML은 content.RenderHtml 메서드가 생성한 것인데, 이는 PDF 문서를 생성합니다.
이제 PDF 생성 논리를 정의했으니 발생할 수 있는 모든 유효성 검사 오류를 처리해 보겠습니다.
유효성 검사 오류 처리
유효성 검사 오류가 발생하면 오류 메시지를 표시하고 유연하게 처리하고자 합니다. Main 메서드를 Program 클래스에서 수정하여 모든 예외를 처리하고 사용자에게 의미 있는 메시지를 표시합시다.
using System;
using System.Collections.Generic;
public class Program
{
static void Main(string[] args)
{
var pdfService = new PdfService();
// Test 1: Empty Customer Name
try
{
var invoiceContent = new InvoiceContent
{
CustomerName = "",
Address = "123 Main St, Anytown, USA",
InvoiceItems = new List<InvoiceItem> {
new InvoiceItem { Description = "Item 1", Price = 19.99M },
new InvoiceItem { Description = "Item 2", Price = 29.99M }
}
};
var pdfDocument = pdfService.GeneratePdf(invoiceContent);
pdfDocument.SaveAs("C:\\TestInvoice.pdf");
Console.WriteLine("PDF generated successfully!");
}
catch (Exception ex)
{
Console.WriteLine("Error generating PDF: " + ex.Message);
}
// Test 2: Empty InvoiceItems
try
{
var invoiceContent = new InvoiceContent
{
CustomerName = "John Doe",
Address = "123 Main St, Anytown, USA",
InvoiceItems = new List<InvoiceItem>() // Empty list
};
var pdfDocument = pdfService.GeneratePdf(invoiceContent);
pdfDocument.SaveAs("C:\\TestInvoice.pdf");
Console.WriteLine("PDF generated successfully!");
}
catch (Exception ex)
{
Console.WriteLine("Error generating PDF: " + ex.Message);
}
// Successful generation
try
{
var invoiceContent = new InvoiceContent
{
CustomerName = "John Doe",
Address = "123 Main St, Anytown, USA",
InvoiceItems = new List<InvoiceItem> {
new InvoiceItem { Description = "Item 1", Price = 19.99M },
new InvoiceItem { Description = "Item 2", Price = 29.99M }
}
};
var pdfDocument = pdfService.GeneratePdf(invoiceContent);
pdfDocument.SaveAs("C:\\TestInvoice.pdf");
Console.WriteLine("PDF generated successfully!");
}
catch (Exception ex)
{
Console.WriteLine("Error generating PDF: " + ex.Message);
}
}
}
using System;
using System.Collections.Generic;
public class Program
{
static void Main(string[] args)
{
var pdfService = new PdfService();
// Test 1: Empty Customer Name
try
{
var invoiceContent = new InvoiceContent
{
CustomerName = "",
Address = "123 Main St, Anytown, USA",
InvoiceItems = new List<InvoiceItem> {
new InvoiceItem { Description = "Item 1", Price = 19.99M },
new InvoiceItem { Description = "Item 2", Price = 29.99M }
}
};
var pdfDocument = pdfService.GeneratePdf(invoiceContent);
pdfDocument.SaveAs("C:\\TestInvoice.pdf");
Console.WriteLine("PDF generated successfully!");
}
catch (Exception ex)
{
Console.WriteLine("Error generating PDF: " + ex.Message);
}
// Test 2: Empty InvoiceItems
try
{
var invoiceContent = new InvoiceContent
{
CustomerName = "John Doe",
Address = "123 Main St, Anytown, USA",
InvoiceItems = new List<InvoiceItem>() // Empty list
};
var pdfDocument = pdfService.GeneratePdf(invoiceContent);
pdfDocument.SaveAs("C:\\TestInvoice.pdf");
Console.WriteLine("PDF generated successfully!");
}
catch (Exception ex)
{
Console.WriteLine("Error generating PDF: " + ex.Message);
}
// Successful generation
try
{
var invoiceContent = new InvoiceContent
{
CustomerName = "John Doe",
Address = "123 Main St, Anytown, USA",
InvoiceItems = new List<InvoiceItem> {
new InvoiceItem { Description = "Item 1", Price = 19.99M },
new InvoiceItem { Description = "Item 2", Price = 29.99M }
}
};
var pdfDocument = pdfService.GeneratePdf(invoiceContent);
pdfDocument.SaveAs("C:\\TestInvoice.pdf");
Console.WriteLine("PDF generated successfully!");
}
catch (Exception ex)
{
Console.WriteLine("Error generating PDF: " + ex.Message);
}
}
}
Imports System
Imports System.Collections.Generic
Public Class Program
Shared Sub Main(ByVal args() As String)
Dim pdfService As New PdfService()
' Test 1: Empty Customer Name
Try
Dim invoiceContent As New InvoiceContent With {
.CustomerName = "",
.Address = "123 Main St, Anytown, USA",
.InvoiceItems = New List(Of InvoiceItem) From {
New InvoiceItem With {
.Description = "Item 1",
.Price = 19.99D
},
New InvoiceItem With {
.Description = "Item 2",
.Price = 29.99D
}
}
}
Dim pdfDocument = pdfService.GeneratePdf(invoiceContent)
pdfDocument.SaveAs("C:\TestInvoice.pdf")
Console.WriteLine("PDF generated successfully!")
Catch ex As Exception
Console.WriteLine("Error generating PDF: " & ex.Message)
End Try
' Test 2: Empty InvoiceItems
Try
Dim invoiceContent As New InvoiceContent With {
.CustomerName = "John Doe",
.Address = "123 Main St, Anytown, USA",
.InvoiceItems = New List(Of InvoiceItem)()
}
Dim pdfDocument = pdfService.GeneratePdf(invoiceContent)
pdfDocument.SaveAs("C:\TestInvoice.pdf")
Console.WriteLine("PDF generated successfully!")
Catch ex As Exception
Console.WriteLine("Error generating PDF: " & ex.Message)
End Try
' Successful generation
Try
Dim invoiceContent As New InvoiceContent With {
.CustomerName = "John Doe",
.Address = "123 Main St, Anytown, USA",
.InvoiceItems = New List(Of InvoiceItem) From {
New InvoiceItem With {
.Description = "Item 1",
.Price = 19.99D
},
New InvoiceItem With {
.Description = "Item 2",
.Price = 29.99D
}
}
}
Dim pdfDocument = pdfService.GeneratePdf(invoiceContent)
pdfDocument.SaveAs("C:\TestInvoice.pdf")
Console.WriteLine("PDF generated successfully!")
Catch ex As Exception
Console.WriteLine("Error generating PDF: " & ex.Message)
End Try
End Sub
End Class
위 코드에서는 try-catch 블록을 사용하여 발생할 수 있는 모든 예외를 잡습니다. 예외가 잡히면, Console.WriteLine을 사용하여 사용자에게 오류 메시지가 표시됩니다.
이제 다양한 시나리오로 이 애플리케이션을 테스트하여 PDF 생성과 유효성 검사 규칙을 검증해 봅시다.
응용 프로그램 테스트
코드 예제에서는 테스트할 세 개의 시나리오가 있습니다:
- 고객명 비어 있음: 고객명을 비워 두어 유효성 검사 오류를 유도합니다.
- 인보이스 항목 비어 있음: 인보이스 항목의 빈 목록을 제공하여 유효성 검사 오류를 유도합니다.
- 성공적인 생성: 유효한 내용을 제공하여 PDF를 성공적으로 생성합니다.
애플리케이션을 실행하고 콘솔의 출력을 확인하십시오.
Error generating PDF: Validation failed:
-- CustomerName: Customer name is required. Severity: Error
Error generating PDF: Validation failed:
-- InvoiceItems: At least one invoice item is required. Severity: Error
PDF generated successfully!
콘솔의 출력 오류
출력 PDF 파일
예상대로 첫 두 가지 시나리오에는 유효성 검사 오류가 표시되고, 세 번째 시나리오에는 성공 메시지가 표시됩니다.
결론
이 튜토리얼에서는 유창한 유효성 검사와 이를 IronPDF와 결합하여 PDF 문서를 생성하는 방법을 탐구했습니다. 콘솔 애플리케이션을 설정하고 PDF 콘텐츠 클래스를 정의하는 것으로 시작합니다. 그런 다음 유창한 유효성 검사로 유효성 검사 규칙을 만들어 다양한 시나리오로 PDF 생성을 테스트합니다.
유창한 유효성 검사는 .NET 애플리케이션에서 객체를 유효성 검사하는 유연하고 사용하기 쉬운 방법을 제공합니다. 유형을 명확히 지정하여 유효성 검사 규칙을 정의하고, 오류 메시지를 사용자 정의하며, 유효성 검사 오류를 유연하게 처리할 수 있습니다.
IronPDF 무료 체험판 및 라이센스 정보는 무료 체험판을 제공하며, 개발자당 라이센스 비용은 $499부터 시작합니다.
자주 묻는 질문
Fluent Validation을 C#에서 PDF 생성과 통합할 수 있는 방법은?
C#에서 Fluent Validation을 PDF 생성과 통합하려면, Visual Studio에서 콘솔 애플리케이션을 설정하고 NuGet을 통해 FluentValidation 및 IronPDF 패키지를 설치한 다음, Fluent Validation을 사용하여 모델 검증 논리를 정의하면서 IronPDF를 사용하여 PDF를 생성할 수 있습니다.
PDF 생성 및 검증을 위해 프로젝트를 설정하는 단계는 무엇인가요?
프로젝트를 설정하려면, Visual Studio에서 새 콘솔 애플리케이션을 만들고 NuGet을 통해 IronPDF 및 FluentValidation 패키지를 설치한 다음, 해당 라이브러리를 사용하여 PDF 콘텐츠와 검증 규칙을 정의합니다.
.NET 라이브러리를 사용하여 HTML 콘텐츠로부터 어떻게 PDF를 생성하나요?
IronPDF의 RenderHtmlAsPdf 메소드를 사용하면 HTML 문자열 또는 파일을 고품질의 PDF로 변환할 수 있습니다.
튜토리얼에서 PdfService 클래스의 목적은 무엇입니까?
튜토리얼의 PdfService 클래스는 먼저 Fluent Validation을 사용하여 콘텐츠를 검증한 후 IronPDF의 ChromePdfRenderer와 RenderHtmlAsPdf 메소드를 사용하여 PDF를 생성하는 역할을 합니다.
Fluent Validation을 사용하여 검증 규칙은 어떻게 정의됩니까?
Fluent Validation에서의 검증 규칙은 AbstractValidator를 상속하는 검증자 클래스를 만들어 정의됩니다. 이 클래스 내에서 RuleFor 메소드를 사용하여 각 속성에 대한 조건을 지정하고, 사용자 정의 오류 메시지와 규칙 체이닝을 허용합니다.
PDF 생성 중에 검증이 실패하면 어떻게 됩니까?
검증이 실패하면 Fluent Validation은 검증 오류에 대한 자세한 정보를 담고 있는 ValidationException을 발생시켜 사용자가 문제의 원인을 알 수 있도록 합니다.
복잡한 객체 검증에 Fluent Validation을 사용할 수 있습니까?
예, Fluent Validation은 자식 검증기를 사용하여 복잡한 객체 검증을 지원하며 모델 내의 중첩된 속성과 컬렉션을 검증할 수 있습니다.
Fluent Validation에서 오류 메시지를 어떻게 맞춤화할 수 있습니까?
Fluent Validation에서 사용자 정의 오류 메시지는 RuleFor로 지정된 각 유효성 검사 규칙에 대해 WithMessage 메서드를 사용하여 정의할 수 있습니다.
PDF 생성 라이브러리에 체험판이 있습니까?
네, IronPDF는 개발자가 라이브러리의 기능을 테스트할 수 있도록 무료 체험판을 제공하며, 라이선스 옵션은 개발자당 $499부터 시작합니다.
IronPDF .NET 10과 완벽하게 호환됩니까?
네. IronPDF는 .NET 10과 완전히 호환되며 윈도우, 리눅스, macOS의 다양한 프로젝트 유형(콘솔, 웹, 데스크톱, Blazor 등)을 지원합니다. 최신 런타임과 별도의 우회 조치 없이 바로 작동합니다.


