跳過到頁腳內容
使用IRONPDF

如何使用IronPDF在C#中使用Fluent Validation

什麼是 Fluent 驗證?

FluentValidation是一個 .NET 驗證函式庫,它有助於建立強型別驗證規則。 它採用流暢的介面和 lambda 表達式,使程式碼更易讀、更易於維護。 您可以不使用模型類別中的資料註解或手動驗證,而是使用 Fluent Validation 為驗證邏輯建立一個單獨的類別。

Fluent Validation 為驗證過程帶來了更大的靈活性。 Fluent Validation 內建了常見場景的驗證器,能夠建立自訂驗證,並且可以輕鬆地將驗證規則串聯起來,是 .NET Core 工具包中一個強大的工具。

了解 Fluent 驗證

Fluent Validation 是一個適用於 .NET 的開源程式庫,它可以輕鬆地為模型類別建立驗證規則。

1.驗證器:驗證器是封裝驗證邏輯的類別。 它們通常是透過繼承 AbstractValidator<t> 基底類別而創建的。 2.規則:規則是屬性必須滿足的驗證條件。 規則是在驗證器類別中使用 RuleFor 方法定義的。 3.驗證失敗:如果規則失敗,Fluent Validation 會建立一個 ValidationFailure 對象,其中包含有關錯誤的詳細信息,包括屬性名稱和錯誤訊息。

什麼是 IronPDF?

IronPDF - Convert HTML to PDF in C#是一個功能強大的 .NET 程式庫,可讓您從 HTML 內容產生 PDF 文件。 無論您需要建立發票、報告或任何其他類型的文檔,IronPDF 都能提供易於使用的解決方案。 它與您的 ASP.NET Core 應用程式無縫集成,使您只需幾行程式碼即可產生高品質的 PDF 檔案。

將 Fluent Validation 與 IronPDF 結合使用

現在我們已經了解了 Fluent Validation 和 IronPDF 是什麼,讓我們看看它們如何一起使用。 本教學將協助建立發票產生器,其中發票內容將使用 ASP.NET Core 中的 FluentValidation 進行驗證,然後再使用 IronPDF 產生 PDF。

設定專案

首先,讓我們在 Visual Studio 或您喜歡的開發環境中建立一個新的控制台應用程式。

  1. 開啟 Visual Studio,然後前往檔案 > 新建 > 專案
  2. 選擇"控制台應用程式(ASP.NET Core)"作為專案模板,並為您的專案提供一個名稱。

    如何在 C# 中使用 Fluent Validation 和 IronPDF,圖 1:建立一個新的控制台應用程式 建立一個新的控制台應用程式

  3. 點選"下一步"按鈕,透過命名項目和選擇儲存庫位置來設定項目。

    如何在 C# 中使用 Fluent Validation 和 IronPDF,圖 2:配置新應用程式 配置新應用程式

  4. 按一下"下一步"按鈕,然後選擇 .NET Framework。 建議使用最新的 .NET Framework (7)。

    如何在 C# 中使用 Fluent Validation 和 IronPDF,圖 3:.NET Framework 選擇 .NET Framework 選擇

  5. 點選"建立"按鈕建立項目。

安裝所需軟體包

專案建立完成後,加入 Fluent Validation 和 IronPDF 所需的 NuGet 套件。

  1. 在解決方案資源管理器中以滑鼠右鍵按一下項目,然後選擇"管理 NuGet 套件"。
  2. 搜尋"FluentValidation",然後點擊"安裝"將該軟體包新增至您的專案。

    如何在 C# 中將 Fluent Validation 與 IronPDF 結合使用,圖 4:在 NuGet 套件管理器 UI 中安裝 FluentValidation 套件 在 NuGet 套件管理器 UI 中安裝 FluentValidation 套件

  3. 同樣地,搜尋" IronPDF - 強大的 .NET PDF 庫",並安裝 IronPDF 軟體包。

或者,您可以使用NuGet 套件管理器控制台,透過以下命令安裝 IronPDF:

Install-Package IronPdf

如何在 C# 中使用 Fluent Validation 和 IronPDF,圖 5:在套件管理器控制台中安裝 IronPDF 套件 在軟體包管理器控制台中安裝 IronPDF 軟體包

專案設定完畢,所需軟體包也已安裝,接下來我們來定義 PDF 內容類。

定義 PDF 內容

在這個範例中,將根據兩個類別中的 HTML 程式碼建立一個簡單的發票 PDF:InvoiceContentInvoiceItem

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
$vbLabelText   $csharpLabel

在上面的程式碼中,定義了一個抽象類別 PdfContent,其中包含一個名為 RenderHtml 的抽象方法。 InvoiceContent 類別繼承自 PdfContent,並表示發票 PDF 的內容。 它包含客戶姓名、地址和發票項目清單等屬性。 InvoiceItem 類別包含兩個屬性:'Description' 和 'Price'。 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
$vbLabelText   $csharpLabel

在原始碼中定義了 InvoiceContentValidator 類,該類繼承自 AbstractValidator<InvoiceContent>。 在驗證器類別的建構函數中,RuleFor 方法定義了 InvoiceContent 類別的每個屬性的驗證規則。

例如,RuleFor(content => content.CustomerName) 指定客戶名稱不能為空。 同樣,也為地址和發票項目屬性定義了驗證規則。

RuleForEach 方法遍歷 InvoiceItems 清單中的每個項目,並套用 InvoiceItemValidatorInvoiceItemValidator 類別包含 InvoiceItem 類別的驗證規則。

有了這些驗證規則,我們接下來使用 IronPDF 產生 PDF。

使用 IronPDF 產生 PDF

IronPDF - 產生和編輯 PDF 文件是一個流行的 .NET 庫,用於建立和操作 PDF 文件。 我們將使用 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
$vbLabelText   $csharpLabel

PdfService 類別提供了一個 GeneratePdf 方法。 此方法接受一個 PdfContent 物件作為輸入,並根據驗證後的內容產生 PDF 文件。

首先,它透過呼叫 GetValidatorForContent 方法來檢索內容的適當驗證器,該方法檢查內容的類型並傳回對應的驗證器。 在我們的案例中,我們支持 InvoiceContent 並使用 InvoiceContentValidator

接下來,透過呼叫驗證器的 Validate 方法來驗證內容。 驗證結果儲存在 ValidationResult 物件中。

如果驗證失敗(!validationResult.IsValid),則會拋出包含驗證錯誤的 FluentValidation.ValidationException。 否則,PDF 將使用 IronPDF 產生。

建立ChromePdfRenderer實例,將 HTML 內容渲染為 PDF。 RenderHtmlAsPdf方法在 renderer 物件上調用,傳入由 content.RenderHtml 方法產生的 HTML,從而產生 PDF 文件。

現在我們已經定義了 PDF 生成邏輯,接下來讓我們處理可能出現的任何驗證錯誤。

處理驗證錯誤

當發生驗證錯誤時,我們希望顯示錯誤訊息並妥善處理它。 讓我們修改 Program 類別的 Main 方法,以便處理任何異常並向使用者顯示有意義的訊息。

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
$vbLabelText   $csharpLabel

在上面的程式碼中,try-catch 區塊用於捕獲可能發生的任何異常。 如果捕獲到異常,將使用 Console.WriteLine 向使用者顯示錯誤訊息。

現在讓我們用不同的場景來測試這個應用程式,以驗證 PDF 產生和驗證規則。

測試應用程式

在程式碼範例中,有三種場景需要測試:

  1. 客戶名稱為空:將客戶名稱留空會觸發驗證錯誤。
  2. 空發票項目:提供一個空的發票項目清單以觸發驗證錯誤。
  3. 生成成功:提供有效內容以成功產生 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!

如何在 C# 中使用 Fluent Validation 和 IronPDF,圖 6:控制台中的輸出錯誤 控制台輸出錯誤

如何在 C# 中使用 Fluent Validation 和 IronPDF,圖 7:輸出的 PDF 文件 輸出的PDF文件

如預期的那樣,前兩種情況會顯示驗證錯誤,而第三種情況會顯示成功訊息。

結論

本教學探討了 Fluent Validation 以及如何將其與 IronPDF 結合使用來產生 PDF 文件。 首先設定控制台應用程式並定義 PDF 內容類別。 然後,使用 Fluent Validation 建立驗證規則,並在不同場景下測試 PDF 產生。

Fluent Validation 為 .NET 應用程式中的物件驗證提供了一種靈活且易於使用的方法。 它允許您以強類型方式定義驗證規則,自訂錯誤訊息,並優雅地處理驗證錯誤。

IronPDF 免費試用和許可資訊提供免費試用,許可起價為每位開發者 499 美元。

常見問題解答

如何在 C#中結合 Fluent Validation 和 PDF 生成?

要在 C#中將 Fluent Validation 與 PDF 生成結合使用,可以在 Visual Studio 中建立 Console Application,通過 NuGet 安裝 FluentValidation 和 IronPDF 包並使用 Fluent Validation 定義模型驗證邏輯,同時使用 IronPDF 生成 PDF。

設置 PDF 生成和驗證專案涉及哪些步驟?

要設置專案,可以在 Visual Studio 中創建新的 Console Application,然後透過 NuGet 安裝 IronPDF 和 FluentValidation 套件,接著使用相應的庫定義 PDF 內容和驗證規則。

如何使用 .NET 庫從 HTML 內容生成 PDF?

你可以使用 IronPDF 的RenderHtmlAsPdf方法從 HTML 內容生成 PDF,這允許將 HTML 字串或文件轉換為高質量的 PDF。

教程中的 PdfService 類的作用是什麼?

教程中的 PdfService 類旨在通過先使用 Fluent Validation 驗證內容來管理 PDF 生成。驗證成功後,它使用 IronPDF 的ChromePdfRendererRenderHtmlAsPdf方法創建 PDF。

如何使用 Fluent Validation 定義驗證規則?

Fluent Validation 中的驗證規則是通過創建繼承自AbstractValidator的驗證器類來定義的。在這個類中,將使用RuleFor方法來指定每個屬性的條件,允許自訂錯誤信息並鏈接規則。

如果在 PDF 生成過程中驗證失敗會發生什麼?

如果驗證失敗,Fluent Validation 將拋出一個ValidationException,其中包含關於驗證錯誤的詳細信息,可以用來通知用戶出了什麼問題。

我可以使用 Fluent Validation 進行複雜物件的驗證嗎?

是的,Fluent Validation 支持通過使用子驗證器進行複雜物件的驗證,允許你驗證模型中的嵌套屬性和集合。

如何在 Fluent Validation 中自訂錯誤信息?

Fluent Validation 中的自訂錯誤信息可以使用WithMessage方法為每個RuleFor指定的驗證規則進行定義。

PDF 生成庫有試用版本嗎?

有,IronPDF 為開發者提供免費試用版本以測試庫的功能,授權選項的價格從每位開發者$499起。

IronPDF 是否與 .NET 10 完全相容?

是的。IronPDF 完全兼容 .NET 10 並支援平台包括 Windows、Linux、macOS 和各種項目類型(控制台、網頁、桌面、Blazor 等)。它可以在最新運行時下開箱即用,無需使用解決方案。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我