跳至頁尾內容
.NET 幫助

C# URL 編碼(開發者如何理解其工作原理)

URL 編碼和解碼是 C# 中用於確保 URL 內資料安全傳輸的技術。 在 C# 中,處理 Web 應用程式、API 呼叫或任何需要安全可靠地透過網路傳輸資料的場景時,經常會遇到這些操作。 在本文中,我們將探討 URL 編碼方法和IronPDF 庫

C# 中的 URL 編碼

對 URL 進行編碼時,會將其字元轉換為可以安全地透過網路發送的形式,從而避免任何誤解。 這是因為網址只能使用 ASCII 字元集透過網際網路傳送。 不屬於此集合的字符,或在 URL 中具有特殊含義的字符(如空格、& 符號和等號),需要使用百分比編碼表示(例如,空格變為%20 )。 C# 提供了內建方法來完成這項任務。

C# 中的 URL 解碼

URL解碼會在到達目的地後將編碼字元還原為原始狀態。 這對於接收應用程式正確理解和處理預期數據至關重要。 解碼將百分比編碼的字元還原成其原始符號,使資料再次可讀可用。

C# 中的編碼方法

在 C# 中,有多種方法可以執行 URL 編碼,每種方法都適用於不同的場景。 這些方法主要存在於System.WebSystem.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 中傳輸。

讓我們透過理解程式碼範例來了解上面描述的前三種編碼方法及其工作原理。

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);
    }
}
$vbLabelText   $csharpLabel

命名空間包含: System.Web命名空間包含在程式碼的開頭。

原始字串:我們定義一個字串變數originalString,其中包含要編碼的字符,以便在 URL 中安全傳輸。 這包括空格和標點符號,如果未經編碼直接包含在 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);
    }
}
$vbLabelText   $csharpLabel

URL 編碼中的字元實體等效項:所示程序轉換 URL 路徑的字串值,將空格轉換為其字元實體等效項 (%20) 以實現 Web 相容性。 這一點至關重要,因為網址不能包含實際的空格字元。

字串值和 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);
    }
}
$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是一個 PDF 庫,它簡化了在 .NET 應用程式中建立、編輯和操作 PDF 文件的過程。 IronPDF 旨在與 C# 和 VB.NET 無縫集成,為開發人員提供從 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");
    }
}
$vbLabelText   $csharpLabel

使用 URL 編碼的工作代碼範例

在下面的範例中,我們將看到如何將 IronPDF 與 URL 編碼結合使用,從網頁產生 PDF。 此場景涉及對 URL 進行編碼,以確保其格式正確,以便進行 Web 請求,然後使用 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}");
    }
}
$vbLabelText   $csharpLabel

C# URL 編碼(開發者運作方式):圖 5 - URL 成功轉換為 PDF 的控制台輸出

程式碼說明

此範例以包含空格的基本 URL 和查詢字串開頭。 使用HttpUtility.UrlEncode對查詢字串進行編碼,以確保其在 URL 中安全傳輸。 對查詢進行編碼後,將其附加到基本 URL 上,形成要存取的完整 URL。

有了完整的、編碼後的 URL,IronPDF 的ChromePdfRenderer就可以取得該 URL 處的網頁並將其轉換為 PDF 文件。 這涉及到創建ChromePdfRenderer類別的實例,然後使用編碼後的 URL 呼叫RenderUrlAsPdf 。 最後,使用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編碼在網頁應用程式中很重要?

URL編碼在網路應用程式中至關重要,因為它能確保URL中傳遞的資料安全無誤地傳輸。它會將不安全字元替換為百分比編碼格式,從而防止潛在的資料損壞或安全性問題。

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

透過在產生 PDF 之前套用 URL 編碼,您可以確保文件中包含的任何 URL 格式正確且傳輸安全。像 IronPDF 這樣的程式庫在將 Web 內容轉換為 PDF 時,就能精確地處理這些 URL。

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

C# 提供了諸如HttpUtility.UrlDecodeUri.UnescapeDataString之類的 URL 解碼方法。這些方法會逆轉編碼過程,將百分比編碼的字元轉換回其原始形式。

URL編碼如何促進API呼叫?

URL 編碼確保查詢參數中的特殊字元能夠安全傳輸,從而防止 API 呼叫過程中出現錯誤。這對於 Web 應用程式中用戶端和伺服器之間可靠地傳遞資料至關重要。

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

是的,IronPDF在將網頁轉換為PDF時可以自動處理URL編碼。它確保URL在PDF生成過程中得到正確的格式化和處理,從而實現與網頁內容的無縫整合。

Jacob Mellor,Team Iron 首席技術官
首席技術長

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。