.NET HELP C# URL Encode (How It Works For Developers) Jacob Mellor 更新:2025年7月28日 下載 IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 URL 編碼和解碼是 C# 中用於確保 URL 內資料安全傳輸的技術。 在 C# 中,處理 Web 應用程式、API 呼叫或任何需要安全可靠地透過網路傳輸資料的場景時,經常會遇到這些操作。 在本文中,我們將探討 URL 編碼方法和IronPDF 庫。 C# 中的 URL 編碼 對 URL 進行編碼時,會將其字元轉換為可以安全地透過網路發送的形式,從而避免任何誤解。 這是因為網址只能使用 ASCII 字元集透過網際網路傳送。 不屬於此集合的字符,或在 URL 中具有特殊含義的字符(如空格、& 符號和等號),需要使用百分比編碼表示(例如,空格變為%20 )。 C# 提供了內建方法來完成這項任務。 C# 中的 URL 解碼 URL解碼會在到達目的地後將編碼字元還原為原始狀態。 這對於接收應用程式正確理解和處理預期數據至關重要。 解碼將百分比編碼的字元還原成其原始符號,使資料再次可讀可用。 C# 中的編碼方法 在 C# 中,有多種方法可以執行 URL 編碼,每種方法都適用於不同的場景。 這些方法主要存在於System.Web和System.Net命名空間中,為開發人員提供了對 URL 進行編碼的彈性。 以下是可用方法的簡要概述: HttpUtility.UrlEncode 方法 (System.Web):這可能是 Web 應用程式中最常用的 URL 編碼方法。 它將字元轉換為百分比編碼格式,使字串可以安全地透過 URL 傳輸。 它在 ASP.NET 專案中尤其有用,可用於對查詢字串和表單參數進行編碼。 HttpUtility.UrlPathEncode 方法 (System.Web):與UrlEncode不同, UrlPathEncode專門用於對 URL 的路徑部分進行編碼,而查詢字串保持不變。 需要注意的是,這種方法不會對整個 URL 進行編碼,而是對路徑部分進行編碼,從而確保 URL 的層次結構得以保留。 Uri.EscapeUriString 方法(系統):此方法用於轉義 URI 字串,將 URI 中不允許的所有字元轉換為其百分比編碼的等效字元。 但是,它不會對某些字元進行編碼,例如斜線( / )和問號( ? ),因為它們被認為是有效的 URI 字元。 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.UrlEncode 或 Uri.EscapeDataString 等方法來編碼 URL。這些方法可將字元轉換成百分比編碼格式,以確保在網際網路上安全傳輸。 URL 編碼與解碼有何差異? URL 編碼會將特殊字符轉換成百分比編碼格式,以確保 URL 中資料傳輸的安全性,而解碼會將這些編碼字符轉換回原始形式,以進行正確的資料詮釋。 如何使用 C# 從 URL 建立 PDF? 您可以使用 IronPDF 在 C# 中將 URL 轉換為 PDF。IronPDF 可讓您直接擷取網頁內容並轉換成 PDF 文件,並整合 URL 編碼技術,以達到精確的網頁請求。 為什麼 URL 編碼在網路應用程式中很重要? URL 編碼在網路應用程式中至關重要,因為它可以確保 URL 中傳輸的資料安全無誤地傳輸。它以百分比編碼格式取代不安全的字元,防止潛在的資料損毀或安全問題。 如何使用 URL 編碼來增強 C# 中 PDF 的產生? 透過在產生 PDF 之前套用 URL 編碼,您可以確保任何包含在文件中的 URL 都能正確格式化並安全傳輸。IronPDF 之類的庫就可以在將網頁內容轉換成 PDF 時準確地處理這些 URL。 C# 中的 URL 解碼有哪些方法? C# 為 URL 解碼提供了 HttpUtility.UrlDecode 和 Uri.UnescapeDataString 等方法。這些方法反轉編碼過程,將百分比編碼的字元轉換回原始形式。 URL 編碼如何促進 API 的呼叫? URL 編碼可確保查詢參數中的特殊字符安全傳輸,防止在 API 呼叫期間發生錯誤。這對於在 Web 應用程式的客戶端和伺服器之間可靠地傳遞資料是非常重要的。 IronPDF 能否在生成 PDF 時自動處理 URL 編碼? 是的,IronPDF 可以在將網頁轉換為 PDF 時自動處理 URL 編碼。它可以確保 URL 在 PDF 生成過程中被正確格式化和處理,提供與網頁內容的無縫整合。 Jacob Mellor 立即與工程團隊聊天 首席技術長 Jacob Mellor 是 Iron Software 的首席技術長,也是開創 C# PDF 技術的有遠見的工程師。作為 Iron Software 核心程式碼庫背後的原始開發人員,他從公司成立之初就塑造了公司的產品架構,與首席執行官 Cameron Rimington 一起將公司轉型為一家 50 多人的公司,為 NASA、Tesla 和全球政府機構提供服務。Jacob 持有曼徹斯特大學土木工程一級榮譽工程學士學位 (BEng)(1998-2001 年)。Jacob 於 1999 年在倫敦開設了他的第一家軟體公司,並於 2005 年創建了他的第一個 .NET 元件,之後,他專門解決微軟生態系統中的複雜問題。他的旗艦產品 IronPDF & Iron Suite for .NET 函式庫在全球的 NuGet 安裝量已超過 3000 萬次,他的基礎程式碼持續為全球使用的開發人員工具提供動力。Jacob 擁有 25 年的商業經驗和 41 年的編碼專業知識,他一直專注於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代的技術領導者。 相關文章 更新2025年12月11日 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 閱讀更多 更新2025年12月20日 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 閱讀更多 更新2025年12月20日 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 閱讀更多 C# Unit Testing (How It Works For Developers)IndexOf C# (How It Works For Developers)
更新2025年12月11日 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 閱讀更多
更新2025年12月20日 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 閱讀更多
更新2025年12月20日 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 閱讀更多