跳過到頁腳內容
.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.WebSystem.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 中安全編碼傳輸。

讓我們了解上述所述的前三種編碼方法及其工作原理,通過理解其代碼示例來理解。

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 命名空間。

原始字符串:我們定義一個名為 originalString 的字符串變量,其中包含要編碼以安全傳輸至 URL 的字符。 這包括如果未編碼的情況下包含在 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

原始 URIoriginalUri 變量以包含空格和特殊字符的查詢字符串初始化一個代表完整 URI 的字符串。 為了確保 URI 能夠正確由網絡瀏覽器和服務器處理,需要對這些特殊字符進行“轉義”。

轉義 URI:調用 Uri.EscapeUriString 方法,参数是 originalUri。 此方法掃描 URI 字符串並將不允許或可能在 URI 中造成歧義的字符進行轉義。

輸出:程序在控制台中輸出原始 URI 及其轉義後的結果。

C# URL 編碼(它對開發者的工作原理):圖 3 - 顯示原始和編碼字符串的控制台輸出

IronPDF:C# PDF 庫

C# URL 編碼(它對開發者的工作原理):圖 4 - IronPDF 網頁

IronPDF 是一個 PDF 庫,可以簡化在 .NET 應用程序中創建、編輯和操作 PDF 文件的過程。 IronPDF 設計可與 C# 和 VB.NET 無縫集成,為開發者提供從 HTML 生成 PDF或者直接從文本生成 PDF 的功能。 無論您是需要自動生成發票、創建動態報告,還是在 .NET 環境中管理文檔,IronPDF 以其易用性和全面的功能集而著稱。

IronPDF 的亮點是其HTML 到 PDF 的轉換功能,保持您的布局和樣式。 這允許從網絡內容創建 PDF,非常適合報告、發票和文檔。 HTML 文件、URL 和 HTML 字符串都可以輕鬆地轉換為 PDFs。

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 編碼的代碼示例

在以下示例中,我們將看到如何將 IronPDF 與 URL 編碼結合使用,從網頁生成 PDF。 此場景涉及編碼 URL 以確保其格式正確地用於網絡請求,然後使用 IronPDF 將該 URL 的內容轉換為 PDF 文檔。

安裝 IronPDF 庫

首先,確保您已在項目中安裝 IronPDF。 如果您正在使用 NuGet 包管理器,您可以通過運行以下命令來安裝它:

Install-Package IronPdf

代碼示例

現在,讓我們深入了解代碼:

using System.Web;
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        License.LicenseKey = "License-Key"; // Set your IronPDF 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;

class Program
{
    static void Main(string[] args)
    {
        License.LicenseKey = "License-Key"; // Set your IronPDF 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

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		License.LicenseKey = "License-Key" ' Set your IronPDF 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}")
	End Sub
End Class
$vbLabelText   $csharpLabel

C# URL 編碼(它對開發者的工作原理):圖 5 - 顯示成功將 URL 轉換為 PDF 的控制台輸出

代碼解釋

該示例以基礎 URL 和包含空格的查詢字符串開始。 使用 HttpUtility.UrlEncode 編碼查詢字符串以確保它在 URL 中安全傳輸。 查詢編碼後,它附加到基礎 URL 上,形成將被訪問的完整 URL。

在準備好完整編碼 URL 後,IronPDF 的 ChromePdfRenderer 用於獲取該 URL 的網頁並將其轉換為 PDF 文檔。 這涉及到創建 ChromePdfRenderer 類的實例,然後調用 RenderUrlAsPdf,傳入編碼的 URL。 最後,使用 SaveAs 方法將生成的 PDF 保存到文件中。 生成的文件是網頁內容的 PDF 文檔,可以通過編碼的 URL 訪問。 這是生成的PDF文件:

C# URL 編碼(它對開發者的工作原理):圖 6 - 由 URL 輸出的 PDF

結論

C# URL 編碼(它對開發者的工作原理):圖 7 - IronPDF 許可頁面

總結來說,C# 提供了強大的 URL 編碼和解碼功能,以確保數據能夠在互聯網上安全高效地傳輸。 通過 System.Web 和 System.Net 命名空間中的內置方法,開發者可以編碼 URL 以防止特殊字符的問題,並將其解碼回原始形式以準確地解釋數據。

對於那些對IronPDF 試用許可優惠感興趣的人,他們可以親身體驗其功能。 如果您決定將 IronPDF 集成到項目中,許可證起價為 $799,提供滿足您在 .NET 框架下的 PDF 處理需求的全面功能套件。

常見問題解答

如何在 C# 中編碼 URL?

在 C# 中,可以使用 HttpUtility.UrlEncodeUri.EscapeDataString 等方法來編碼 URL。這些方法將字符轉換為百分比編碼格式,以確保在互聯網上的安全傳輸。

URL 編碼和解碼之間有什麼差別?

URL 編碼將特殊字符轉換為百分比編碼格式,以確保在 URL 中的安全數據傳輸,而解碼則將這些編碼字符轉回其原始形式以便正確解釋數據。

如何使用 C# 從 URL 建立 PDF?

可以使用 IronPDF 在 C# 中將 URL 轉換為 PDF。IronPDF 允許你直接捕獲網頁的內容並將其轉換為 PDF 文件,並整合 URL 編碼技術以確保準確的 web 請求。

為什麼 URL 編碼在 web 應用程式中如此重要?

URL 編碼在 web 應用程式中至關重要,因為它確保在 URL 中傳遞的數據可以安全無誤地傳輸。它將不安全字符替換為百分比編碼格式,以防止潛在的數據損壞或安全問題。

如何在 C# 中利用 URL 編碼增強 PDF 生成?

在生成 PDF 之前應用 URL 編碼,以確保文檔中包含的任何 URL 均已正確格式化並安全傳輸。像 IronPDF 這樣的庫可以在將網頁內容轉換為 PDF 時準確處理這些 URL。

C# 中有哪些可用的 URL 解碼方法?

C# 提供 HttpUtility.UrlDecodeUri.UnescapeDataString 等方法用於 URL 解碼。這些方法將百分比編碼字符轉回其原始形式,逆轉編碼過程。

URL 編碼如何促進 API 調用?

URL 編碼確保查詢參數中的特殊字符能安全傳輸,防止 API 調用時的錯誤。這對於在 web 應用程式中可靠傳遞客戶端與伺服器之間的數據至關重要。

IronPDF 能否在生成 PDF 時自動處理 URL 編碼?

是的,IronPDF 能夠在將網頁轉換為 PDF 時自動處理 URL 編碼。它確保 URL 在 PDF 生成過程中正確格式化和處理,提供與 web 內容的無縫整合。

Curtis Chau
技術作家

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

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