.NET ヘルプ

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

更新済み 4月 3, 2024
共有:

イントロダクション

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): これはおそらく、Webアプリケーションで最も一般的に使用されているURLエンコーディングの方法です。 文字をパーセントエンコード形式に変換し、URL経由での送信が安全になるようにします。 ASP.NETプロジェクトで、クエリ文字列やフォームパラメータをエンコードするのに特に役立ちます。

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

  3. Uri.EscapeUriString メソッド (システム): このメソッドはURI文字列をエスケープするために使用され、URI内で許可されていないすべての文字をパーセントエンコードされた等価文字に変換します。 ただし、スラッシュのような特定の文字はエンコードしません。 (/* /) そして疑問符 (応答できません。内容を提供してください。)考慮されるため、有効なURI文字です。

  4. Uri.EscapeDataString メソッド (システム): このメソッドは、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
VB   C#

名前空間のインクルード: コードの冒頭にSystem.Web名前空間が含まれています。

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

エンコード: HttpUtility.UrlEncode メソッドは originalString を引数にして呼び出されます。 以下のメソッドは文字列を処理し、セキュリティ上不適切な文字をパーセントエンコードされた文字に置き換えた新しい文字列を返します。 例えば、スペースは%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
VB   C#

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
VB   C#

オリジナル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から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
VB   C#

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}")
VB   C#

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をプロジェクトに統合することを決定した場合、ライセンスは$liteLicenseから始まり、.NETフレームワーク内でPDF操作のニーズを満たす包括的な機能セットを提供します。

< 以前
C# 単体テスト (開発者はどのように機能するか)
次へ >
IndexOf C#(開発者向けの動作方法)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >