.NET 帮助

C# URL 编码(它是如何为开发人员工作的)

发布 2024年四月3日
分享:

简介

URL 编码 和解码是 C# 中用于确保 URL 内数据安全传输的技术。在 C# 中,处理网络应用程序、API 调用或任何需要安全可靠地通过互联网传递数据的场景时,通常会遇到这些操作。在本文中,我们将探讨 URL 编码方法和 IronPDF 库.

C&num 中的 URL 编码;

对 URL 进行编码时,就是将其字符转换为可在互联网上安全发送的形式,以避免任何误解。这是因为 URL 只能使用 ASCII 字符集在互联网上发送。不属于该字符集的字符,或在 URL 中具有特殊含义的字符 (如空格、逗号和等号),需要使用百分比编码来表示 (例如,空格变为 %20).C# 提供了完成这一任务的内置方法。

C&num 中的 URL 解码;

URL 解码将编码字符转换回到达目的地时的原始状态。这对于接收应用程序正确理解和处理数据至关重要。解码将百分比编码字符变回原始符号,使数据可读可用。

C&num 中的编码方法;

在 C# 中,有多种执行 URL 编码的方法,每种方法都适用于不同的情况。这些方法主要存在于System.WebSystem.Net命名空间中,为开发人员提供了对 URL 进行编码的灵活性。以下是可用方法的简要概述:

  1. HttpUtility.UrlEncode 方法 (System.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
VB   C#

包含命名空间:代码开头包含System.Web命名空间。

原始字符串:我们定义了一个字符串变量 originalString,其中包含为在 URL 中安全传输而编码的字符。其中包括空格和标点符号,如果不进行编码,这些字符可能会在 URL 中出现问题。

编码:以 originalString 作为参数调用 HttpUtility.UrlEncode 方法。该方法会处理字符串并返回一个新字符串,其中不安全字符会被替换为相应的百分比编码字符。例如,空格会被替换为%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 字符串处理: 原始路径变量的字符串值为"/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#

原始 URI:原始 URIoriginalUri** 变量的初始化值是一个代表完整 URI 的字符串,包括带有空格和特殊字符的查询字符串。为确保网络浏览器和服务器能正确处理 URI,需要对这些特殊字符进行 "转义 "处理。

转义 URI:以originalUri为参数调用Uri.EscapeUriString方法。该方法会扫描 URI 字符串,并转义 URI 中不允许使用或可能导致歧义的字符。

输出:程序会将原始 URI 和转义 URI 打印到控制台。

C# URL 编码(如何为开发人员工作):图 3 - 控制台输出显示原始字符串和编码字符串

IronPDF:C# PDF Library

C# URL 编码(开发人员如何使用):图 4 - IronPDF 网页

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");
    }
}
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 编码的工作代码示例

在下面的示例中,我们将看到如何结合 URL 编码使用 IronPDF 从网页生成 PDF。该示例涉及对 URL 进行编码,以确保其格式符合 Web 请求,然后使用 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# 单元测试(它如何为开发人员工作)
下一步 >
C# 中的 IndexOf(开发人员如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >