Server.URLEncode和HttpUtility.UrlEncode
Server.URLEncode方法会在一个字符串上应用URL的编码规则, 包括转义字符.
URLEncode会如下转换字符:
- 空格( )会被转换为加号(+)
- 非字母数字字符会被转换为他们的十六进制表现形式
举例:
<%Response.Write(Server.URLEncode("http://www.microsoft.com")) %>
输出结果为
http%3A%2F%2Fwww%2Emicrosoft%2Ecom
HttpUtility.UrlEncode方法可以被用来编码整个URL, 包括查询字符串值(query-string values). 诸如空格和其他的标点符号传入HTTP stream的时候, 他们可能会被误解析为流的结尾. URL encoding会把这些URL中不允许出现的字符转换为等同的字符实体. URL decoding会执行逆操作.
你可以使用UrlEncode()方法或UrlPathEncode()方法. 然而, 这两个方法的返回值是不同的.
UrlEncode()方法会把空格转换为加号(+).
UrlPathEncode()方法会把空格转换为字符串"%20", 这也是空格的十六进制的表示方式.
你应该在对URL中的path部分编码时使用UrlPathEncode()方法, 这样能确保不论在什么平台或浏览器上执行解码的时候, 都会得到一个合法的URL.
两个方法的区别
他们之间没有什么具体的区别. Server.UrlEncode的存在是因为需要与经典的ASP兼容.
HttpServerUtility.UrlEncode
会在内部调用HttpUtility.UrlEncode.
摘自MSDN:
URL encoding ensures that all browsers will correctly transmit text in URL strings. Characters such as a question mark (?), ampersand (&), slash mark (/), and spaces might be truncated or corrupted by some browsers. As a result, these characters must be encoded in <a> tags or in query strings where the strings can be re-sent by a browser in a request string.
UrlEncode is a convenient way to access the HttpUtility..::.UrlEncode method at run time from an ASP.NET application. Internally, UrlEncode uses HttpUtility..::.UrlEncode to encode strings.
Server.URLEncode Method
http://msdn.microsoft.com/en-us/library/ms525738.aspx
HttpUtility.UrlEncode Method (String)
http://msdn.microsoft.com/en-us/library/4fkewx0t.aspx
HttpServerUtility.UrlEncode Method (String)
http://msdn.microsoft.com/en-us/library/zttxte6w.aspx
Server.UrlEncode vs. HttpUtility.UrlEncode
http://stackoverflow.com/questions/602642/server-urlencode-vs-httputility-urlencode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律