透かしなしで本番環境でテストしてください。
必要な場所で動作します。
30日間、完全に機能する製品をご利用いただけます。
数分で稼働させることができます。
製品トライアル期間中にサポートエンジニアリングチームへの完全アクセス
FluentValidation (フルーエントバリデーション)は、厳密に型指定された検証ルールの構築を支援する.NET検証ライブラリです。 これは流暢なインターフェースとラムダ式を提供することで実現され、コードをより読みやすく、保守しやすくします。 モデルクラスでデータ注釈や手動検証を使用する代わりに、Fluent Validation を使用して検証ロジック用の別のクラスを作成できます。
Fluent Validationは、バリデーションの分野により柔軟性をもたらします。 組み込みのバリデーターで一般的なシナリオに対応し、カスタムバリデーションを構築する能力、そしてバリデーションルールをチェーンする簡単な方法を備えたFluent Validationは、.NET Coreツールキットの強力なツールです。
Fluent Validationは、モデルクラスのバリデーションルールを簡単に構築できるオープンソースの.NETライブラリです。
バリデーター: バリデーターは、検証ロジックをカプセル化するクラスです。 AbstractValidator
から継承することによって通常作成されます。
ルール: ルールとは、プロパティが満たさなければならない検証条件のことです。 ルールは、バリデータクラス内のRuleFor
メソッドを使用して定義されます。
ValidationFailure
オブジェクトを作成します。IronPDF - C#でHTMLをPDFに変換は、HTMLコンテンツからPDF文書を生成できる強力な.NETライブラリです。 請求書、レポート、その他どのような種類のドキュメントを作成する必要がある場合でも、IronPDFは使いやすいソリューションを提供します。 それは、ASP.NET Core アプリケーションとシームレスに統合され、わずか数行のコードで高品質なPDFファイルを生成できます。
では、Fluent ValidationとIronPDFがどのようなものか理解したところで、それらを一緒に使用する方法を見てみましょう。 このチュートリアルでは、請求書生成ツールを構築する際に、FluentValidationを使用してASP.NET Coreで請求書の内容が検証され、IronPDFを使用してPDFを生成する方法を紹介します。
それでは、始めましょう!
まずは、Visual Studio またはお好みの開発環境で新しいコンソールアプリケーションを作成しましょう。
Visual Studio を開き、ファイル > 新規作成 > プロジェクトに進みます。
"Console App" を選択(ASP.NET Core)「プロジェクトテンプレートを選択し、プロジェクトに名前を付けてください。」
新しいコンソールアプリケーションを作成
Next ボタンをクリックして、プロジェクトに名前を付け、リポジトリの場所を選択して設定してください。
アプリケーションの新しい構成
次へボタンをクリックして、.NET Frameworkを選択してください。 最新の .NET Framework(7)推奨されます。
.NETフレームワークの選択
プロジェクトが作成されたら、Fluent ValidationおよびIronPDFの必要なNuGetパッケージを追加する必要があります。
ソリューションエクスプローラーでプロジェクトを右クリックし、「NuGet パッケージの管理」を選択します。
「FluentValidation」を検索し、「インストール」をクリックしてパッケージをプロジェクトに追加します。
NuGet パッケージ マネージャー UI で FluentValidation パッケージをインストールする
同様に、"IronPDF - 強力な.NET PDFライブラリ" をクリックし、IronPDFパッケージをインストールしてください。
しかし、次のコマンドを使用してNuGet パッケージ マネージャー コンソールを使ってIronPDFをインストールすることもできます:
Install-Package IronPdf
パッケージマネージャーコンソールでIronPDFパッケージをインストール
プロジェクトのセットアップと必要なパッケージのインストールが完了したら、PDFコンテンツクラスの定義に進みましょう。
この例では、InvoiceContent
とInvoiceItem
という新しい2つのクラスのHTMLコードから簡単な請求書PDFが作成されます。
public abstract class PdfContent
{
public abstract string RenderHtml();
}
public class InvoiceContent : PdfContent
{
public string CustomerName { get; set; }
public string Address { get; set; }
public List<InvoiceItem> InvoiceItems { get; set; }
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; }
}
public abstract class PdfContent
{
public abstract string RenderHtml();
}
public class InvoiceContent : PdfContent
{
public string CustomerName { get; set; }
public string Address { get; set; }
public List<InvoiceItem> InvoiceItems { get; set; }
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
と呼ばれるバリデータークラスを作成します。 このクラスは AbstractValidator
から継承されます。Fluent Validation
が提供するもの。
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
から継承されています。. バリデータクラスのコンストラクタ内部で、
RuleForメソッドは
InvoiceContent` クラス各プロパティに対する検証ルールを定義します。
例: RuleFor(内容 => 内容.CustomerName)
顧客名が空であってはならないという新しいルールを定義できます。 Fluent Validation
も NotEmpty
メソッドを連鎖してこのバリデーションルールを指定することができます。 同様に、住所や請求書項目のプロパティに対してもバリデーションルールを定義します。
請求書の項目を検証するために、RuleForEach
メソッドを使用して、InvoiceItems
リスト内の各項目を反復処理し、InvoiceItemValidator
というバリデーターを適用します。 InvoiceItemValidator
クラスは別に定義されており、InvoiceItem
クラスのバリデーションルールを含んでいます。
これらの検証ルールを設定したら、IronPDFを使用してPDFの生成に進みましょう。
IronPDF - PDFドキュメントの生成と編集は PDF ドキュメントの作成および操作のための人気のある .NET ライブラリです。 IronPDFは、検証済みの請求書コンテンツに基づいてPDFを生成するために使用されます。
using IronPdf;
using FluentValidation;
public class PdfService
{
public PdfDocument GeneratePdf<T>(T content) where T : PdfContent
{
var validator = GetValidatorForContent(content);
FluentValidation.Results.ValidationResult validationResult = validator.Validate(content);
if (!validationResult.IsValid)
{
throw new FluentValidation.ValidationException(validationResult.Errors);
}
var renderer = new ChromePdfRenderer();
return renderer.RenderHtmlAsPdf(content.RenderHtml());
}
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
{
public PdfDocument GeneratePdf<T>(T content) where T : PdfContent
{
var validator = GetValidatorForContent(content);
FluentValidation.Results.ValidationResult validationResult = validator.Validate(content);
if (!validationResult.IsValid)
{
throw new FluentValidation.ValidationException(validationResult.Errors);
}
var renderer = new ChromePdfRenderer();
return renderer.RenderHtmlAsPdf(content.RenderHtml());
}
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(クロームPDFレンダラー)HTMLコンテンツをPDFとしてレンダーする。 私たちはそれを呼びますRenderHtmlAsPdf(HTMLをPDFとしてレンダリング)htmlToPdf
オブジェクトのメソッドを使用し、content.RenderHtml
メソッドによって生成されたHTMLを引数として渡します。 これによりPDFドキュメントが生成されます。
PDF生成ロジックを定義したので、発生する可能性のある検証エラーを処理しましょう。
バリデーションエラーが発生したとき、エラーメッセージを表示し、優雅に処理したいです。 Program
クラスの Main
メソッドを修正して、エラーを処理し、ユーザーに意味のあるメッセージを表示しましょう。
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
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);
}
}
}
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
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生成とバリデーションルールを検証しましょう。
このコード例では、テストするシナリオが三つあります:
顧客名が空です: 検証エラーを引き起こすために顧客名を空のままにします。
空の請求書項目:検証エラーを発生させるために、空の請求書項目のリストが提供されています。
生成の成功: 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ファイル
予想通り、最初の二つのシナリオでは検証エラーが表示され、三つ目のシナリオでは成功メッセージが表示されます。
このチュートリアルでは、Fluent Validationを調査し、IronPDFを使用してPDF文書を生成する方法を学びました。 コンソールアプリケーションを設定し、PDFコンテンツクラスを定義することから始めます。 次に、Fluent Validationを使用して検証ルールを作成し、さまざまなシナリオでPDF生成をテストしました。
Fluent Validationは、.NETアプリケーションにおけるオブジェクトのバリデーションに対して柔軟で使いやすいアプローチを提供します。 強く型付けされた方法で検証ルールを定義し、エラーメッセージをカスタマイズし、検証エラーを優雅に処理することができます。
IronPDF 無料トライアルとライセンス情報は無料トライアルを提供しており、ライセンスは開発者1人あたり499ドルからとなっています。