.NET 帮助 C# URL编码(开发人员如何使用) Curtis Chau 已更新:七月 28, 2025 Download IronPDF NuGet 下载 DLL 下载 Windows 安装程序 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article URL 编码 和解码是 C# 中用于确保在 URL 中安全传输数据的技术。 在 C# 中,当处理 Web 应用程序、API 调用或任何需要在互联网上安全可靠传输数据的场景时,通常会遇到这些操作。 在本文中,我们将探讨 URL 编码方法和 IronPDF 库。 C#中的 URL 编码 当你对 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 方法 (System):此方法旨在对 URI 字符串进行转义,将所有不允许在 URI 中的字符转换为其百分比编码的等价物。 然而,它不会编码某些字符,如斜线 (/) 和问号 (?),因为它们被认为是有效的 URI 字符。 Uri.EscapeDataString 方法 (System):此方法用于编码要在 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。 输出:最后,程序将原始字符串和编码后的字符串一起打印到控制台。 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 进行编码以适应网络传输的直接示例,解决空格和其他特殊字符可能引入的问题。 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 被 Web 浏览器和服务器正确处理,这些特殊字符需要被“转义”。 转义 URI:调用 Uri.EscapeUriString 方法,并传入 originalUri 作为参数。 此方法扫描 URI 字符串并转义不被允许或可能在 URI 中引起模棱两可的字符。 输出:程序将原始 URI 和转义后的 URI 一起打印到控制台。 IronPDF:C# PDF库 IronPDF 是一个简化在 .NET 应用程序中创建、编辑和操作 PDF 文件的 PDF 库。 设计为与 C# 和 VB.NET 无缝集成,IronPDF 为开发人员提供从 HTML 生成 PDF 或直接从文本生成 PDF 的功能。 无论您是需要自动化生成发票、创建动态报告,还是在 .NET 环境中管理文档,IronPDF 都以其易用性和全面功能集脱颖而出。 IronPDF 的亮点是其 HTML 到 PDF 的转换 功能,保留您的布局和样式。 这允许从 Web 内容创建 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 包管理器,可以运行以下命令来安装它: 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 代码解释 示例从基础 URL 和包含空格的查询字符串开始。 查询字符串使用HttpUtility.UrlEncode 编码,以确保其在 URL 中安全传输。 在编码查询后,将其附加到基础 URL 形成完整的将被访问的 URL。 在准备好完整的编码 URL 后,使用 IronPDF 的 ChromePdfRenderer 来提取该 URL 上的网页并将其转换为 PDF 文档。 这涉及创建一个 ChromePdfRenderer 类的实例,然后调用 RenderUrlAsPdf 方法处理编码 URL。 最后,使用 SaveAs 方法将生成的 PDF 保存到文件中。 结果文件是一个通过编码 URL 可以访问的网页内容的 PDF 文档。 以下是输出的 PDF 文件: 结论 总之,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#提供方法如HttpUtility.UrlDecode和Uri.UnescapeDataString用于URL解码。这些方法反转编码过程,将百分比编码字符转换回其原始形式。 URL编码如何促进API调用? URL编码确保查询参数内的特殊字符能够安全传输,防止API调用期间出现错误。这对于保证在网络应用中客户端和服务器之间可靠地传输数据至关重要。 IronPDF在生成PDF时能否自动处理URL编码? 是的,IronPDF在将网页转换为PDF时可以自动处理URL编码。它确保URL在PDF生成过程中被正确格式化和处理,与网页内容无缝集成。 Curtis Chau 立即与工程团队聊天 技术作家 Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。 相关文章 已更新九月 4, 2025 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多 已更新九月 4, 2025 C# String Equals(开发者用法) 与强大的 PDF 库 IronPDF 结合使用,切换模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 阅读更多 已更新八月 5, 2025 C# Switch 模式匹配(开发者用法) 与强大的 PDF 库 IronPDF 结合使用,切换模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 阅读更多 C# 单元测试(开发人员如何使用)IndexOf C#(开发人员如何使用)
已更新九月 4, 2025 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多