【发布时间】:2010-05-20 09:22:31
【问题描述】:
我正在开发一个客户端应用程序,该应用程序使用 restful 服务按名称查找公司。 能够在查询中包含文字和符号很重要,因为这个字符在公司名称中很常见。
但是,每当我将 %26(URI 转义的 & 字符)传递给 System.Uri 时,它都会将其转换回常规 & 字符!仔细观察,唯一没有被转换回来的两个字符是哈希 (%23) 和百分比 (%25)。
假设我想搜索一家名为“Pierce & Pierce”的公司:
var endPoint = "http://localhost/companies?where=Name eq '{0}'";
var name = "Pierce & Pierce";
Console.WriteLine(new Uri(string.Format(endPoint, name)));
Console.WriteLine(new Uri(string.Format(endPoint, name.Replace("&", "%26"))));
Console.WriteLine(new Uri(string.Format(endPoint, Uri.EscapeUriString(name))));
Console.WriteLine(new Uri(string.Format(endPoint, Uri.EscapeDataString(name))));
以上四种组合均返回:
http://localhost/companies?where=Name eq 'Pierce & Pierce'
这会导致服务器端出现错误,因为 & 号被(正确地)解释为查询 arg 分隔符。我真正需要它返回的是原始字符串:
http://localhost/companies?where=Name eq 'Pierce %26 Pierce'
如何在不完全丢弃 System.Uri 的情况下解决此问题?
我不能在最后一刻用 %26 替换所有与号,因为通常会涉及多个查询参数,我不想破坏它们的分隔符。
注意:在this question 中讨论了类似的问题,但我特指System.Uri。
【问题讨论】:
标签: .net escaping uri query-string