.NET ヘルプ

C# URLエンコード(開発者向けの動作方法)

イントロダクション

URLエンコーディング およびデコードは、C#内でデータをURL内で安全に送信するために使用される技術です。 C#では、これらの操作は一般的にウェブアプリケーション、API呼び出し、またはデータをインターネット経由で安全かつ信頼性を持って渡す必要があるシナリオでよく見られます。 この記事では、URLエンコード方法とIronPDFライブラリについて探ります。

C#でのURLエンコーディング

URLをエンコードする際には、インターネット上で安全に送信できる形式に文字を変換し、誤解を避けるようにします。 これは、URLがASCII文字セットを使用してのみインターネット経由で送信されるためです。 このセットに含まれない文字、またはURLで特別な意味を持つ文字(スペース、アンパサンド、イコール記号など)は、パーセントエンコーディングを使用して表す必要があります(例: スペースは%20になります)。 C# はこのタスクを達成するための組み込みメソッドを提供します。

C#におけるURLデコード

URLデコードは、目的地に到達した際に、エンコードされた文字を元の状態に戻します。 受信アプリケーションがデータを正しく理解し、意図したとおりに処理するために、これは不可欠です。 デコードはパーセントエンコードされた文字を元の記号に戻し、データを再び読み取り可能で使用可能にします。

C#におけるエンコーディングメソッド

C#には、様々なシナリオに適した複数のURLエンコード方法があります。 これらのメソッドは主にSystem.WebおよびSystem.Net名前空間に存在し、開発者にURLのエンコード方法において柔軟性を提供します。 以下に利用可能なメソッドの概要を示します:

  1. HttpUtility.UrlEncode メソッド (System.Web): これはウェブアプリケーションで URL エンコーディングに最も一般的に使用されるメソッドです。 文字をパーセントエンコード形式に変換し、URL経由での送信が安全になるようにします。 ASP.NETプロジェクトで、クエリ文字列やフォームパラメータをエンコードするのに特に役立ちます。

  2. HttpUtility.UrlPathEncode メソッド (System.Web): UrlEncode とは異なり、UrlPathEncode は URL のパス部分のみをエンコードするように設計されており、クエリ文字列はそのまま残します。 このメソッドはURL全体をエンコードするのではなく、パスの部分をエンコードすることに注意が必要です。これにより、URLの階層構造が保持されます。

  3. Uri.EscapeUriString メソッド (System): このメソッドは、URI 文字列をエスケープし、URI に許可されていないすべての文字をパーセントエンコードされた等価の文字に変換することを目的としています。 しかし、スラッシュ(/)やクエスチョンマーク(?)などの特定の文字はエンコードされません。これらは有効なURI文字とみなされるためです。

  4. Uri.EscapeDataString メソッド (System): このメソッドは、URIのクエリ部分で使用される文字列をエンコードするために設計されています。 これは、RFC 3986で定義された予約されていない文字を除くすべての文字をエンコードします。これはEscapeUriStringよりも積極的であり、データがURL内での送信に安全にエンコードされることを保証します。

    上記で説明された最初の3つのエンコーディング方法とその動作を、コード例を理解することで見てみましょう。

HttpUtility.UrlEncode メソッドのコード例

using System;
using System.Web;
class Program
{
    static void Main()
    {
        string originalPath = "/api/search/Hello World!";
        string encodedPath = UrlEncode(originalPath);
        Console.WriteLine("Original Path: " + originalPath);
        Console.WriteLine("Encoded Path: " + encodedPath);
    }
    public static string UrlEncode(string originalString)
    {
        return HttpUtility.UrlEncode(originalString);
    }
}
using System;
using System.Web;
class Program
{
    static void Main()
    {
        string originalPath = "/api/search/Hello World!";
        string encodedPath = UrlEncode(originalPath);
        Console.WriteLine("Original Path: " + originalPath);
        Console.WriteLine("Encoded Path: " + encodedPath);
    }
    public static string UrlEncode(string originalString)
    {
        return HttpUtility.UrlEncode(originalString);
    }
}
Imports System
Imports System.Web
Friend Class Program
	Shared Sub Main()
		Dim originalPath As String = "/api/search/Hello World!"
		Dim encodedPath As String = UrlEncode(originalPath)
		Console.WriteLine("Original Path: " & originalPath)
		Console.WriteLine("Encoded Path: " & encodedPath)
	End Sub
	Public Shared Function UrlEncode(ByVal originalString As String) As String
		Return HttpUtility.UrlEncode(originalString)
	End Function
End Class
$vbLabelText   $csharpLabel

ネームスペースのインクルード: コードの冒頭でSystem.Webネームスペースがインクルードされています。

元の文字列:URLでの安全な送信のためにエンコードする文字を含む文字列変数originalStringを定義します。 これは、エンコードせずにURLに含まれると問題を引き起こす可能性のあるスペースや句読点を含みます。

エンコーディング: originalString を引数として HttpUtility.UrlEncode メソッドが呼び出されます。 以下のメソッドは文字列を処理し、セキュリティ上不適切な文字をパーセントエンコードされた文字に置き換えた新しい文字列を返します。 例えば、スペースは%20に置き換えられます。

出力: 最後に、プログラムは元の文字列とエンコードされた文字列の両方をコンソールに出力します。

C# URL エンコード(開発者向け: その仕組み):図 1 - 元の文字列とエンコードされた文字列を示すコンソール出力

HttpUtility.UrlPathEncode メソッドのコード例

using System;
using System.Web;
class Program
{
    static void Main()
    {
        // Define the original URL path, which includes spaces.
        string originalPath = "/api/search/Hello World!";
        // Use the HttpUtility.UrlPathEncode method to encode the path.
        string encodedPath = HttpUtility.UrlPathEncode(originalPath);
        // Output the original and encoded paths to the console.
        Console.WriteLine("Original Path: " + originalPath);
        Console.WriteLine("Encoded Path: " + encodedPath);
    }
}
using System;
using System.Web;
class Program
{
    static void Main()
    {
        // Define the original URL path, which includes spaces.
        string originalPath = "/api/search/Hello World!";
        // Use the HttpUtility.UrlPathEncode method to encode the path.
        string encodedPath = HttpUtility.UrlPathEncode(originalPath);
        // Output the original and encoded paths to the console.
        Console.WriteLine("Original Path: " + originalPath);
        Console.WriteLine("Encoded Path: " + encodedPath);
    }
}
Imports System
Imports System.Web
Friend Class Program
	Shared Sub Main()
		' Define the original URL path, which includes spaces.
		Dim originalPath As String = "/api/search/Hello World!"
		' Use the HttpUtility.UrlPathEncode method to encode the path.
		Dim encodedPath As String = HttpUtility.UrlPathEncode(originalPath)
		' Output the original and encoded paths to the console.
		Console.WriteLine("Original Path: " & originalPath)
		Console.WriteLine("Encoded Path: " & encodedPath)
	End Sub
End Class
$vbLabelText   $csharpLabel

URLエンコーディングにおける文字実体等価物: 示されたプロセスは、URLパスの文字列値を変換し、スペースをウェブ互換性のためにその文字実体等価物(%20)に変換します。 これは重要です。なぜなら、URLには実際のスペース文字を含めることができないからです。

文字列の値とURL文字列の処理: originalPath 変数の文字列値は "/api/search/Hello World!" であり、スペースが含まれているためエンコードが必要な典型的なURL文字列の例です。

この例では、メソッドのオーバーロードを持たない特定のバージョンのHttpUtility.UrlPathEncodeを使用していますが、URLパスをエンコードするためのメソッドの設計意図に注意することが重要です。 開発者は、メソッドオーバーロードが存在する場合、それを認識しておくべきです。メソッドオーバーロードは、異なる種類の入力を受け入れたり、追加の機能を提供したりすることで、メソッドを使用するための代替手段を提供します。

オブジェクトのエンコーディングと文字列URLの変換: このコンテキストでのエンコーディングオブジェクトは、HttpUtility.UrlPathEncodeメソッドの操作に暗黙的に含まれており、このメソッドは文字列URLを受け取り、そのエンコード形式を返します。 このメソッドは、特殊文字を適切な表現にエンコードしながらURLパスの構造を保持することを保証します。

エンコードされたパスの出力: プログラムは、元のパスからエンコードされたパスへの変換を示します。 これは、スペースやその他の特殊文字が生じさせる可能性のある問題に対応しながら、ウェブ送信のために文字列URLをエンコードする直接的な例です。

C# URL エンコード(開発者向けの仕組み):図 2 - 元の文字列とエンコードされた文字列を表示するコンソール出力

URI.EscapeUriString メソッドのコード例

using System;
class Program
{
    static void Main()
    {
        string originalUri = "https://example.com/search?query=Hello World!";
        string escapedUri = Uri.EscapeUriString(originalUri);
        Console.WriteLine("Original URI: " + originalUri);
        Console.WriteLine("Escaped URI: " + escapedUri);
    }
}
using System;
class Program
{
    static void Main()
    {
        string originalUri = "https://example.com/search?query=Hello World!";
        string escapedUri = Uri.EscapeUriString(originalUri);
        Console.WriteLine("Original URI: " + originalUri);
        Console.WriteLine("Escaped URI: " + escapedUri);
    }
}
Imports System
Friend Class Program
	Shared Sub Main()
		Dim originalUri As String = "https://example.com/search?query=Hello World!"
		Dim escapedUri As String = Uri.EscapeUriString(originalUri)
		Console.WriteLine("Original URI: " & originalUri)
		Console.WriteLine("Escaped URI: " & escapedUri)
	End Sub
End Class
$vbLabelText   $csharpLabel

オリジナルURI: originalUri 変数は、スペースや特殊文字を含むクエリ文字列を含むフルURIを表す文字列で初期化されます。 URIがWebブラウザやサーバーによって正しく処理されるようにするためには、これらの特殊文字を「エスケープ」する必要があります。

URIのエスケープ: Uri.EscapeUriString メソッドが originalUri を引数として呼び出されます。 このメソッドはURI文字列をスキャンし、URIで許可されていない文字や曖昧さを引き起こす可能性のある文字をエスケープします。

出力: プログラムは、元のURIとエスケープされたURIの両方をコンソールに表示します。

C# URL エンコード(開発者向けの動作確認方法):図3 - 元の文字列とエンコードされた文字列を表示するコンソール出力

IronPDF: C# PDFライブラリ

C# URL エンコード (開発者向けの使用方法): 図 4 - IronPDF ウェブページ

IronPDFは、.NETアプリケーション内でPDFファイルの作成、編集、および操作を簡素化するPDFライブラリです。 C#およびVB.NETとシームレスに統合するように設計されているIronPDFは、開発者にHTMLからPDFを生成する機能やテキストから直接生成する機能を提供します。 請求書の自動生成、動的レポートの作成、または.NET環境での文書管理が必要な場合、IronPDFはその使いやすさと包括的な機能セットで際立っています。

IronPDFのハイライトは、そのHTML to PDF変換機能であり、レイアウトとスタイルを維持します。 これはウェブコンテンツからPDFを作成することを可能にし、レポート、請求書、および文書化に最適です。 HTMLファイル、URL、およびHTML文字列を簡単にPDFに変換できます。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

URLエンコードの作業コード例

以下の例では、URLエンコーディングを使用してIronPDFと連携し、ウェブページからPDFを生成する方法を紹介します。 シナリオは、URLをエンコードしてウェブリクエストに適した形式にした後、IronPDFを使用してそのURLのコンテンツをPDFドキュメントに変換するというものです。

IronPDFライブラリのインストール

まず、プロジェクトにIronPDFをインストールしていることを確認してください。 NuGetパッケージマネージャーを使用している場合は、次のコマンドを実行してインストールできます:

Install-Package IronPdf

コード例

それでは、コードに入りましょう:

using System.Web;
using IronPdf;
License.LicenseKey = "License-Key";
string baseUrl = "https://example.com/search";
// The query parameter with spaces that needs to be encoded
string query = "Hello World!";
// Encoding the query parameter to ensure the URL is correctly formatted
string encodedQuery = HttpUtility.UrlEncode(query);
// Constructing the full URL with the encoded query parameter
string fullUrl = $"{baseUrl}?query={encodedQuery}";
// Initialize the IronPDF HtmlToPdf renderer
var renderer = new ChromePdfRenderer();
// Convert the web page at the encoded URL to a PDF document
var pdf = renderer.RenderUrlAsPdf(fullUrl);
// Save the PDF to a file
string filePath = "webpage.pdf";
pdf.SaveAs(filePath);
Console.WriteLine($"PDF successfully created from: {fullUrl}");
Console.WriteLine($"Saved to: {filePath}");
using System.Web;
using IronPdf;
License.LicenseKey = "License-Key";
string baseUrl = "https://example.com/search";
// The query parameter with spaces that needs to be encoded
string query = "Hello World!";
// Encoding the query parameter to ensure the URL is correctly formatted
string encodedQuery = HttpUtility.UrlEncode(query);
// Constructing the full URL with the encoded query parameter
string fullUrl = $"{baseUrl}?query={encodedQuery}";
// Initialize the IronPDF HtmlToPdf renderer
var renderer = new ChromePdfRenderer();
// Convert the web page at the encoded URL to a PDF document
var pdf = renderer.RenderUrlAsPdf(fullUrl);
// Save the PDF to a file
string filePath = "webpage.pdf";
pdf.SaveAs(filePath);
Console.WriteLine($"PDF successfully created from: {fullUrl}");
Console.WriteLine($"Saved to: {filePath}");
Imports System.Web
Imports IronPdf
License.LicenseKey = "License-Key"
Dim baseUrl As String = "https://example.com/search"
' The query parameter with spaces that needs to be encoded
Dim query As String = "Hello World!"
' Encoding the query parameter to ensure the URL is correctly formatted
Dim encodedQuery As String = HttpUtility.UrlEncode(query)
' Constructing the full URL with the encoded query parameter
Dim fullUrl As String = $"{baseUrl}?query={encodedQuery}"
' Initialize the IronPDF HtmlToPdf renderer
Dim renderer = New ChromePdfRenderer()
' Convert the web page at the encoded URL to a PDF document
Dim pdf = renderer.RenderUrlAsPdf(fullUrl)
' Save the PDF to a file
Dim filePath As String = "webpage.pdf"
pdf.SaveAs(filePath)
Console.WriteLine($"PDF successfully created from: {fullUrl}")
Console.WriteLine($"Saved to: {filePath}")
$vbLabelText   $csharpLabel

C# URL エンコード(開発者向けの動作方法):図 5 - URLをPDFに変換する成功時のコンソール出力

コードの説明

例は、ベースURLとスペースを含むクエリ文字列から始まります。 クエリ文字列は、HttpUtility.UrlEncode を使用してエンコードされ、URLで安全に送信されることを保証します。 クエリがエンコードされた後、ベースURLに追加され、アクセスされる完全なURLが形成されます。

エンコードされたURLが準備できたら、IronPDFのChromePdfRendererレンダラーを使用して、そのURLのウェブページを取得し、PDFドキュメントに変換します。 これには、ChromePdfRenderer クラスのインスタンスを作成し、エンコードされたURLを使って RenderUrlAsPdf を呼び出すことが含まれます。 最後に、生成されたPDFはSaveAsメソッドを使用してファイルに保存されます。 結果として得られるファイルは、エンコードされたURLを通じてアクセス可能な、ウェブページの内容を含むPDFドキュメントです。 こちらが出力されたPDFファイルです。

C# URL エンコード (開発者向けの動作): 図6 - URLから出力されたPDF

結論

C# URL エンコード(開発者向けの仕組み):図7 - IronPDFライセンスページ

まとめると、C#はURLエンコードおよびデコードの強力な機能を提供し、データをインターネット上で安全かつ効率的に送信できるようにします。 System.WebおよびSystem.Net名前空間内の組み込みメソッドを使用して、開発者はURLをエンコードして特殊文字に関する問題を防止し、元の形式にデコードして正確なデータ解釈を行うことができます。

興味のある方には、IronPDF トライアル ライセンス提供が利用可能で、その機能を直接評価する機会を提供します。 IronPDFをプロジェクトに統合することに決めた場合、ライセンスは$749から始まり、.NETフレームワーク内でPDF操作のニーズを満たす包括的な機能スイートを提供します。

チペゴ
ソフトウェアエンジニア
チペゴは優れた傾聴能力を持ち、それが顧客の問題を理解し、賢明な解決策を提供する助けとなっています。彼は情報技術の学士号を取得後、2023年にIron Softwareチームに加わりました。現在、彼はIronPDFとIronOCRの2つの製品に注力していますが、顧客をサポートする新しい方法を見つけるにつれて、他の製品に関する知識も日々成長しています。Iron Softwareでの協力的な生活を楽しんでおり、さまざまな経験を持つチームメンバーが集まり、効果的で革新的な解決策を提供することに貢献しています。チペゴがデスクを離れているときは、良い本を楽しんだり、サッカーをしていることが多いです。
< 以前
C# 単体テスト (開発者はどのように機能するか)
次へ >
IndexOf C#(開発者向けの動作方法)