在生产环境中测试,无水印。
随时随地满足您的需求。
获得30天的全功能产品。
几分钟内就能启动并运行。
在您的产品试用期间,全面访问我们的支持工程团队。
URL 编码 和解码是在 C# 中使用的技术,以确保在 URL 中的数据安全传输。 在 C# 中,在处理网络应用程序、API 调用或任何需要安全可靠地通过互联网传递数据的场景时,通常会遇到这些操作。 在本文中,我们将探讨URL编码方法和IronPDF library。
对 URL 进行编码时,需要将其字符转换为可在互联网上安全发送的形式,以避免任何误解。 因为 URL 只能使用 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方法(System):此方法用于对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 中包含这些符号而不进行编码,可能会引起问题。
编码:使用 originalString 作为参数调用 HttpUtility.UrlEncode 方法。 该方法会处理字符串并返回一个新字符串,其中不安全的字符会被替换为相应的百分比编码字符。 例如,空格被替换为%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 不能包含实际的空格字符。
字符串值和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:调用 Uri.EscapeUriString 方法,并将 originalUri 作为其参数。 这种方法会扫描 URI 字符串,并转义不允许使用或可能导致 URI 含糊不清的字符。
输出:程序将原始URI和转义的URI都打印到控制台。
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
在下面的示例中,我们将看到如何结合 URL 编码使用 IronPDF 从网页生成 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}")
C# URL 编码(开发人员如何使用):图 5 - URL 转换为 PDF 成功后的控制台输出
示例以基本 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操作需求。