在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
URL 編碼和解碼是 C# 中的技術,用於確保在 URL 中安全傳輸數據。 在 C# 中,這些操作通常在處理網路應用程式、API 呼叫或任何需要通過網際網路安全可靠地傳遞資料的情境中遇到。 在本文中,我們將探討 URL 編碼方法和IronPDF 庫。
當您編碼一個網址時,您會將其字元更改為可安全傳送到互聯網上的形式,以避免任何誤解。 這是因為網址只能使用 ASCII 字符集通過互聯網發送。 不屬於此集合的字符,或是在URL中具有特殊含義的字符(如空格、&符號和等號),需要使用百分比編碼來表示(例如,空格變成 %20)。 C# 提供內建的方法來完成這個任務。
URL 解碼將編碼的字符轉換回它們到達目的地時的原始狀態。 這對於接收應用程式正確理解和處理數據至關重要。 解碼將百分比編碼的字符轉換回其原始符號,使數據再次可讀和可用。
在 C# 中,有多種方法可以執行 URL 編碼,每種方法適合不同的情境。 這些方法主要位於System.Web和System.Net命名空間中,為開發人員提供了編碼 URL 的靈活性。 以下是可用方法的簡要概述:
HttpUtility.UrlEncode 方法 (System.Web):這可能是網頁應用程式中最常用的用於URL編碼的方法。 它將字元轉換為百分比編碼格式,使字串在透過URL傳輸時變得安全。 在 ASP.NET 專案中,對查詢字串和表單參數進行編碼特別有用。
HttpUtility.UrlPathEncode 方法 (System.Web):不同於 UrlEncode,UrlPathEncode 專為編碼 URL 的路徑部分而設計,不會影響查詢字串。 需要注意的是,這個方法不會編碼整個URL,而是只編碼路徑部分,以確保URL的層次結構得以保存。
Uri.EscapeUriString 方法(系統):此方法用於轉譯 URI 字串,將 URI 中不允許的所有字元轉換為其百分比編碼的等同字元。 但是,它不會編碼某些字元,例如斜線(/)和問號(?),因為它們被視為有效的 URI 字元。
Uri.EscapeDataString 方法 (System):這個方法是用於將字串編碼以用於 URI 的查詢部分。 它會對除 RFC 3986 中定義的未保留字符以外的所有字符進行編碼。這比EscapeUriString更具攻擊性,確保數據在 URL 中傳輸時被安全編碼。
讓我們了解上述的前三種編碼方法及其工作原理,通過理解其代碼示例。
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
命名空间包含:代碼開頭包括 System.Web 命名空间。
原始字串:我們定義了一個字串變數originalString,其包含要編碼以便在 URL 中安全傳輸的字符。 這包括可能在未編碼情況下包含在 URL 中而導致問題的空格和標點符號。
編碼:HttpUtility.UrlEncode 方法以 originalString 作為其參數被調用。 此方法會處理字串,並返回一個將不安全字符替換為其百分比編碼等效值的新字串。 例如,空格被替換為%20。
輸出:最後,程式將原始字串和編碼字串都列印到控制台。
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
URL 編碼中的字符實體等價物: 所示的過程將 URL 路徑的字串值轉換為網頁相容的字符實體等價物(%20)。 這很重要,因為網址不能包含真正的空格字符。
字串值和 URL 字串處理: originalPath 變數的字串值是 "/api/search/Hello World!",這是因為包含空格而需要編碼的 URL 字串的典型範例。
儘管此範例使用了無方法重載的特定版本的HttpUtility.UrlPathEncode,但重要的是要注意該方法在設計上是為了對 URL 路徑進行編碼。 開發人員應該注意方法重載的存在,因為它們提供了使用方法的替代方式,通常通過接受不同類型的輸入或提供額外的功能。
編碼物件與字串 URL 轉換:在這個上下文中,編碼物件隱含於 HttpUtility.UrlPathEncode 方法的操作中,該方法接受字串 URL 並回傳其編碼形式。 此方法確保在編碼特殊字符為其適當表示時,URL 路徑的結構保持不變。
編碼路徑輸出: 此程式展示了從原始路徑轉換為編碼路徑的過程。 這是一個將字串 URL 編碼以適應網路傳輸的直接範例,解決空格和其他特殊字元可能引入的潛在問題。
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
原始 URI:originalUri 變數以表示完整 URI 的字串初始化,其中包括含有空格和特殊字元的查詢字串。 為了確保 URI 能夠被網絡瀏覽器和伺服器正確處理,這些特殊字符需要被「轉義」。
轉譯 URI:使用 originalUri 作為參數調用 Uri.EscapeUriString 方法。 此方法掃描 URI 字串並對在 URI 中不允許或可能引起歧義的字元進行轉義。
輸出:程式將原始和轉義的 URI 同時列印至控制台。
IronPDF 是一個 PDF 函式庫,可簡化在 .NET 應用程式中創建、編輯和操作 PDF 檔案。 IronPDF 設計為與 C# 和 VB.NET 無縫整合,為開發人員提供了從HTML 生成 PDF或直接從文字生成 PDF 的功能。 無論您需要自動化發票生成、創建動態報告,或是在 .NET 環境中管理文件,IronPDF 因其易於使用和全面的功能集而脫穎而出。
IronPDF 的亮點是其HTML 到 PDF 轉換功能,保持您的佈局和樣式。 這允許從網路內容創建 PDF,非常適合用於報告、發票和文件。 HTML 檔案、URLs 和 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
在以下範例中,我們將看到如何使用IronPDF結合URL編碼來從網頁生成PDF。 此情境涉及編碼 URL 以確保其正確格式化用於網頁請求,然後使用 IronPDF 將該 URL 的內容轉換為 PDF 文件。
首先,確保您的專案中已安裝 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}")
範例從基礎 URL 和包含空格的查詢字串開始。 查詢字串使用HttpUtility.UrlEncode編碼,以確保其在 URL 中安全傳輸。 將查詢編碼後,會將其附加到基礎 URL 上,以形成將被訪問的完整 URL。
準備好完整的編碼 URL 後,IronPDF 的ChromePdfRenderer 渲染器用於獲取該 URL 的網頁並將其轉換為 PDF 文件。 這涉及創建一個 ChromePdfRenderer 類的實例,然後調用 RenderUrlAsPdf 並傳入編碼的 URL。 最後,生成的 PDF 使用 SaveAs 方法儲存到檔案中。 生成的檔案是網頁內容的 PDF 文件,可通過編碼的 URL 訪問。 這是輸出 PDF 檔案:
總結來說,C# 提供了強大的 URL 編碼和解碼功能,確保數據能夠在互聯網上安全且高效地傳輸。 透過 System.Web 和 System.Net 命名空間中的內建方法,開發人員可以編碼 URL 以防止特殊字符引起的問題,並將其解碼為原始形式以進行準確的數據解釋。
對於那些有興趣探索的人,IronPDF 試用許可證提供是可用的,提供了一個親自評估其功能的機會。 如果您決定將 IronPDF 整合到您的項目中,許可證價格從 $749 開始,提供完整的功能套件,以滿足您在 .NET 框架中的 PDF 操作需求。