跳過到頁腳內容
.NET幫助

C# URL 編碼(對於開發者的運行原理)

URL 編碼和解碼是 C# 中用來確保 URL 內資料安全傳輸的技術。 在 C# 中,當處理 Web 應用程式、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):這可能是 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);
    }
}
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 中,可能會導致問題。

編碼:呼叫HttpUtility.UrlEncode方法,並將originalString作為參數。 此方法會處理字串並傳回新字串,其中不安全的字元會以其百分比編碼的等效字元取代。 例如,空格以 %20 取代。

輸出:最後,程式會將原始字串和編碼後的字串都印到控制台。

C# URL 編碼 (How It Works For Developers):圖 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 編碼 (How It Works For Developers):圖 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,這些特殊字符需要"轉義"。

轉義 URI:呼叫Uri.EscapeUriString方法,並將originalUri作為其參數。 此方法會掃描 URI 字串,並將 URI 中不允許使用或可能造成歧義的字元轉義。

輸出:程式會將原始 URI 和轉義後的 URI 同時列印到控制台。

C# URL 編碼 (How It Works For Developers):圖 3 - 顯示原始與編碼字串的控制台輸出

IronPDF:C## PDF 函式庫。

C# URL 編碼 (How It Works For Developers):圖 4 - IronPDF 網頁

IronPDF 是一個 PDF 函式庫,可簡化在 .NET 應用程式中建立、編輯和處理 PDF 檔案的工作。 IronPDF 旨在與 C# 和 VB.NET 無縫整合,為開發人員提供從 HTML 產生 PDF 或直接從文字產生 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
$vbLabelText   $csharpLabel

使用 URL 編碼的工作程式碼範例

在下面的範例中,我們將看到如何使用 IronPDF 與 URL 編碼結合,從網頁產生 PDF。 此方案涉及對 URL 進行編碼,以確保其格式符合 Web 請求,然後使用 IronPDF 將該 URL 中的內容轉換為 PDF 文件。

安裝 IronPDF 函式庫

首先,確保您的專案已安裝 IronPDF。 如果您使用 NuGet Package Manager,您可以執行下列步驟來安裝:

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 編碼 (How It Works For Developers):圖 5 - 成功將 URL 轉換為 PDF 的控制台輸出

說明程式碼

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

在完整的編碼 URL 準備就緒後,IronPDF 的 ChromePdfRenderer 將用來取得該 URL 的網頁,並將其轉換成 PDF 文件。 這包括建立 ChromePdfRenderer 類的實體,然後以編碼的 URL 來呼叫 RenderUrlAsPdf。 最後,使用 SaveAs 方法將產生的 PDF 儲存為檔案。 所產生的檔案是網頁內容的 PDF 文件,可透過編碼的 URL 存取。 以下是輸出的 PDF 檔案:

C# URL 編碼 (How It Works For Developers):圖 6 - 從 URL 輸出 PDF

結論

C# URL 編碼 (How It Works For Developers):圖 7 - IronPDF 授權頁面

總而言之,C# 提供了強大的 URL 編碼和解碼功能,確保資料可以安全且有效率地在網際網路上傳輸。 透過 System.Web 和 System.Net 命名空間內的內建方法,開發人員可以對 URL 進行編碼,以防止出現特殊字符的問題,並將 URL 解碼為原始形式,以進行準確的資料詮釋。

對於那些有興趣探索 IronPDF 試用授權產品的人,這些產品提供了第一手評估其功能的機會。 如果您決定將 IronPDF 整合到您的專案中,許可證起價為 $999,它提供了一套全面的功能,以滿足您在 .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 內容的無縫整合。

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

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我