.NET 幫助

C# URL 編碼(開發人員如何操作)

發佈 2024年4月3日
分享:

簡介

URL 編碼 在 C# 中,編碼和解碼是用於確保數據在 URL 中安全傳輸的技術。在 C# 中,這些操作通常在處理網頁應用程式、API 呼叫或任何需要通過互聯網安全可靠地傳輸數據的情境下遇到。在本文中,我們將探討 URL 編碼方法和 IronPDF library.

在 C# 中的 URL 編碼

當你對 URL 進行編碼時,你將其字符改變為一種可以安全傳送至網際網路的形式,避免任何誤解。這是因為 URL 只能使用 ASCII 字符集在網際網路上傳送。不屬於此集合的字符或在 URL 中具有特殊意義的字符 (如空格、和號以及等號),需使用百分比編碼表示 (例如, 空格變成 %20)C# 提供了內建的方法來完成這項任務。

C# 中的URL解碼

URL解碼將編碼字符返回其到達目的地時的原始狀態。這對於接收應用程式正確理解和處理數據是必不可少的。解碼將百分比編碼字符轉換回原始符號,使數據再次可讀和可用。

C# 中的编码方法

在 C# 中,有多種方式可以執行 URL 編碼,每種方式適合不同的情境。這些方法主要存在於 System.WebSystem.Net 命名空間內,為開發人員提供了編碼 URL 的靈活性。以下是可用方法的簡要概述:

  1. **HttpUtility.UrlEncode 方法 (系統.Web) 在 Web 應用程式中,這可能是最常用的 URL 編碼方法。它將字符轉換為百分比編碼格式,使字符串在 URL 中傳輸時更安全。在 ASP.NET 專案中特別有用,因為它可以編碼查詢字符串和表單參數。

  2. HttpUtility.UrlPathEncode 方法 (系統.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
VB   C#

命名空間包含: 在程式碼的開頭包含了 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);
    }
}
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#

原始 URIoriginalUri 變數初始化為表示完整 URI 的字串,包括帶有空格和特殊字元的查詢字串。為了確保 URI 被網頁瀏覽器和伺服器正確處理,這些特殊字元需要進行 '轉碼'。

轉碼 URI:使用 Uri.EscapeUriString 方法,其參數為 originalUri。該方法會掃描 URI 字串並轉碼那些在 URI 中不允許或可能引起歧義的字元。

輸出:程式將原始 URI 和轉碼後的 URI 都輸出到控制台。

C# URL 編碼(如何為開發人員工作):圖 3 - 顯示原始和編碼字符串的控制台輸出

IronPDF:C# PDF 庫

C# URL 編碼(開發人員如何使用):圖4 - IronPDF 網頁

IronPDF 是一個PDF庫,簡化了在 .NET 應用程式中創建、編輯和操作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 編碼的工作代碼範例

在以下範例中,我們將看到如何結合使用 IronPDF 和 URL 編碼從網頁生成 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 類的實例,然後調用 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 整合到您的項目中,授權費用自 $749 起,提供全方位的功能來滿足您在 .NET 框架內的 PDF 操作需求。

< 上一頁
C# 單元測試(開發者如何運作)
下一個 >
IndexOf C#(如何為開發人員工作)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >