43、Server.UrlEncode、HttpUtility.UrlDecode的区别?

Server.UrlEncode 和 HttpUtility.UrlDecode 是 .NET 中用于处理 URL 编码/解码的两个不同方法,主要区别在于所属命名空间、使用场景和具体行为。以下是详细对比:

1. 所属类库与命名空间

Server.UrlEncode

  • 属于 System.Web.HttpServerUtility 类。
  • 通常通过 HttpContext.Current.Server(ASP.NET Web Forms)或
    Page.Server(ASP.NET 页面)访问。
  • 命名空间: System.Web
  • 适用场景: 传统 ASP.NET Web Forms 或经典 ASP.NET 应用程序。

HttpUtility.UrlDecode

  • 属于 System.Web.HttpUtility 类。
  • 是一个静态工具方法,可直接调用(如 HttpUtility.UrlDecode(string))。
  • 命名空间: System.Web
  • 适用场景: 更通用的 URL 解码,适用于 ASP.NET Web Forms、MVC、.NET Core(需通过兼容包)等。

2. 功能方向

Server.UrlEncode

  • 功能: 对字符串进行 URL 编码(将特殊字符转换为 %XX 格式)。
  • 示例:
csharp 复制代码
string encoded = Server.UrlEncode("Hello World&"); // 输出 "Hello%20World%26"

HttpUtility.UrlDecode

  • 功能: 对已编码的 URL 字符串进行 解码(将 %XX 还原为原始字符)。
  • 示例:
csharp 复制代码
string decoded = HttpUtility.UrlDecode("Hello%20World%26"); // 输出 "Hello World&"

3. 注意事项

.NET Core/5+ 的变化

  • Server.UrlEncode 和 HttpUtility 在 .NET Core 中不再默认包含,需通过 System.Web 兼容包或改用 WebUtility 类(位于 System.Net 命名空间)。

  • 推荐在新项目中使用 WebUtility.UrlEncode 和 WebUtility.UrlDecode。

编码/解码的互补性

  • 编码和解码通常是成对使用的。例如:
csharp 复制代码
string original = "data&";
string encoded = HttpUtility.UrlEncode(original); // 编码
string decoded = HttpUtility.UrlDecode(encoded); // 解码回原始值

4. 代码示例对比

csharp 复制代码
// ASP.NET Web Forms 中使用 Server.UrlEncode
string safeParam = Server.UrlEncode("name=John Doe");
Response.Redirect($"Page.aspx?{safeParam}");

// 通用场景中使用 HttpUtility.UrlDecode
string encodedParam = Request.QueryString["param"];
string originalParam = HttpUtility.UrlDecode(encodedParam);

总结

  • Server.UrlEncode:用于编码,依赖 HttpServerUtility,适合传统 ASP.NET
  • HttpUtility.UrlDecode:用于解码,静态方法,适用性更广。
  • 现代替代方案:在 .NET Core/5+ 中优先使用 WebUtility 类。

根据项目类型选择合适的方法,并注意平台兼容性。

相关推荐
小白不白11128 分钟前
C# WinForm 与 VP 二次开发
开发语言·c#
SunnyDays10111 小时前
如何使用 C# 自动调整 Excel 行高和列宽
开发语言·c#·excel
itgather2 小时前
OfficeExcel — Word / Excel DLL 验证台功能介绍
c#·word·excel
云中小生2 小时前
Scrutor:.NET 依赖注入自动化的优雅实现
c#·.net
郝亚军2 小时前
Visual Studio 2022项目中的.sln是什么?
c++·c#·visual studio
jghhh013 小时前
C# 图片水印工具(支持9个位置)
数据库·microsoft·c#
步步为营DotNet3 小时前
Semantic Kernel 在.NET AI 开发中的深度探索与实践
人工智能·.net
咸鱼翻身小阿橙3 小时前
C# WinForms 控件学习项目
开发语言·学习·c#
半亩码田3 小时前
【.NET新特性·第5篇】.NET 9 速览:云原生与性能之年
云原生·.net
JaydenAI3 小时前
[MAF预定义Agent中间件-03]FunctionInvocationDelegatingAgent:将AOP引入函数调用
ai·c#·agent·aop·maf