C#でIronPDFを使用してFluent Validationを使用する方法
Fluent Validationとは?
FluentValidationは、強く型指定された検証ルールの作成を手助けする.NET検証ライブラリです。 流暢なインターフェースとラムダ式を使い、コードをより読みやすく、保守しやすくします。 モデルクラスでデータ注釈や手動検証を使用する代わりに、Fluent Validationを使用して検証論理のための別のクラスを作成できます。
Fluent Validationは検証における柔軟性を向上させます。 一般的なシナリオに対応したビルドインバリデーター、カスタムバリデーションの作成機能、バリデーションルールを簡単に連鎖する方法を提供し、Fluent Validationは.NET Coreツールキットの強力なツールです。
Fluent Validationの理解
Fluent Validationは、モデルクラスのための検証ルールを簡単に作成するための.NET向けオープンソースライブラリです。
- バリデーター: バリデーターは検証ロジックをカプセル化するクラスです。
AbstractValidator基底クラスを継承することで、通常作成されます。 - ルール: ルールはプロパティが満たすべき条件です。 ルールはバリデータークラス内で
RuleForメソッドを使って定義されます。 - バリデーションエラー: ルールが失敗した場合、Fluent Validationはエラーの詳細を含む
ValidationFailureオブジェクトを作成します。
IronPDFとは何ですか?
IronPDF - Convert HTML to PDF in C#はHTMLコンテンツからPDFドキュメントを生成できる強力な.NETライブラリです。 請求書やレポート、その他の文書を作成する必要がある場合、IronPDFは使いやすいソリューションを提供します。 ASP.NET Coreアプリケーションとシームレスに統合され、わずか数行のコードで高品質なPDFファイルを生成できます。
Fluent ValidationとIronPDFの使用法
Fluent ValidationとIronPDFが何であるかを理解したところで、それらを一緒に使用する方法を見てみましょう。 このチュートリアルでは、FluentValidationをASP.NET Coreで使用して請求書の内容を検証し、IronPDFを使ってPDFを生成する請求書ジェネレーターを構築します。
プロジェクトのセットアップ
まず、Visual Studioまたはお好みの開発環境で新しいコンソールアプリケーションを作成します。
- Visual Studioを開き、ファイル > 新規作成 > プロジェクトに進みます。
- プロジェクトテンプレートとして"Console App (ASP.NET Core)"を選択し、プロジェクトの名前を指定します。
新しいコンソール アプリケーションを作成する
- 次へボタンをクリックし、プロジェクトを命名してリポジトリの場所を選択して構成します。
新しいアプリケーションの構成
- 次へボタンをクリックし、.NETフレームワークを選択します。 最新の.NETフレームワーク(7)が推奨されます。
.NET Framework の選択
- 作成ボタンをクリックしてプロジェクトを作成します。
必要なパッケージのインストール
プロジェクトが作成されたら、Fluent ValidationとIronPDFのための必要なNuGetパッケージを追加します。
- ソリューションエクスプローラーでプロジェクトを右クリックし、"NuGetパッケージの管理"を選択します。
- "FluentValidation"を検索し、"インストール"をクリックしてパッケージをプロジェクトに追加します。
NuGetパッケージマネージャーUIでFluentValidationパッケージをインストールします
- 同様にして"IronPDF - Powerful .NET PDF Library"を検索し、IronPDFパッケージをインストールします。
あるいは、NuGetパッケージマネージャーコンソールを使用してIronPDFをインストールできます。以下のコマンドを使用します:
Install-Package IronPdf
パッケージマネージャーコンソールでIronPdfパッケージをインストールします
プロジェクトがセットアップされ、必要なパッケージがインストールされたので、PDFコンテンツクラスの定義に進みましょう。
PDF コンテンツの定義
この例では、InvoiceContentおよびInvoiceItemの2つのクラスで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; }
}上記のコードでは、RenderHtmlという抽象メソッドを持つ抽象PdfContentクラスが定義されています。 InvoiceContentクラスはPdfContentを拡張し、請求書PDFの内容を表します。 顧客の名前、住所、および請求書項目のリストのプロパティを持っています。 InvoiceItemクラスには、'Description'と'Price'の2つのプロパティがあります。 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.");
}
}ソースコードでは、InvoiceContentValidatorクラスが定義されており、AbstractValidator<InvoiceContent>を継承します。 バリデータークラスのコンストラクタ内で、RuleForメソッドがInvoiceContentクラスの各プロパティの検証ルールを定義します。
例えば、RuleFor(content => content.CustomerName)は顧客名が空でないことを指定します。 同様に、住所および請求書項目のプロパティに対しても検証ルールが定義されています。
RuleForEachメソッドは、InvoiceItemsリスト内の各項目を繰り返し、InvoiceItemValidatorを適用します。 InvoiceItemValidatorクラスはInvoiceItemクラスの検証ルールを含んでいます。
これらの検証ルールが整ったら、IronPDFを使用したPDF生成に進みましょう。
IronPDFを使用してPDFを生成する
IronPDF - Generate and Edit PDF Documentsは、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.");
}
}
}PdfServiceクラスはGeneratePdfメソッドを提供します。 このメソッドはPdfContentオブジェクトを入力として受け取り、検証済みのコンテンツに基づいてPDFドキュメントを生成します。
まず、GetValidatorForContentメソッドを呼び出して適切な検証器を取得し、コンテンツの種類を確認し、対応する検証器を返します。 私たちの場合、InvoiceContentをサポートし、InvoiceContentValidatorを使用します。
次に、バリデーターのValidateメソッドを呼び出してコンテンツを検証します。 検証結果はValidationResultオブジェクトに格納されます。
もし検証が失敗した場合(!validationResult.IsValid)、検証エラーを含むFluentValidation.ValidationExceptionがスローされます。 それ以外の場合、IronPDFを使用してPDFが生成されます。
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);
}
}
}上記のコードでは、発生する可能性のある例外をキャッチするためにtry-catchブロックが使用されています。 例外がキャッチされた場合、Console.WriteLineを使用してユーザーにエラーメッセージが表示されます。
このアプリケーションを異なるシナリオでテストして、PDF生成と検証ルールを確認しましょう。
アプリケーションのテスト
コード例では、テストする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!
コンソールの出力エラー
出力PDFファイル
予想通り、最初の2つのシナリオでは検証エラーが表示され、3番目のシナリオでは成功メッセージが表示されます。
結論
このチュートリアルでは、Fluent ValidationとそれをIronPDFで使用してPDF文書を生成する方法を探りました。 コンソールアプリケーションを設定し、PDFコンテンツクラスを定義することから始めました。 次に、Fluent Validationを使用して検証ルールを作成し、さまざまなシナリオでPDF生成をテストしました。
Fluent Validationは.NETアプリケーションでオブジェクトを検証するための柔軟で使いやすいアプローチを提供します。 強く型付けされた方法で検証ルールを定義し、エラーメッセージをカスタマイズし、検証エラーを優雅に処理することができます。
IronPDF Free Trial & Licensing Information は無料トライアルを提供し、ライセンスは1人の開発者あたり499ドルから始まります。
よくある質問
C#でFluent Validationを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でコンテンツを検証した後、PDFを生成する管理を目的としています。検証に成功した場合、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と完全に互換性があり、Windows、Linux、macOSを含むプラットフォームを、様々なプロジェクトタイプ(コンソール、Web、デスクトップ、Blazorなど)でサポートしています。最新のランタイムでも、特別な回避策を必要とせずにすぐに使用できます。









