特殊字符编码比例在URL发送前 [英] Percentage Encoding of special characters before sending it in the URL

查看:136
本文介绍了特殊字符编码比例在URL发送前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我需要通过特殊字符,如#,!在等网址Facebook,Twitter和这样的社交网站。对于我与URL逃生codeS取代这些字符。

 返回valToEn code.Replace(!,%21)。更换(#,%23)
   .Replace($,%24)替换。(与&,%26)
   .Replace(',%27)。替换((,%28)
   。.Replace(),%29)更换(*,2A%);

I need to pass special characters like #,! etc in URL to Facebook,Twitter and such social sites. For that I am replacing such characters with URL Escape Codes.
return valToEncode.Replace("!", "%21").Replace("#", "%23") .Replace("$", "%24").Replace("&", "%26") .Replace("'", "%27").Replace("(", "%28") .Replace(")", "%29").Replace("*", "%2A");

它为我,但我想这样做更efficiently.Is有任何其他的方式来逃避这种角色?我试着用 Server.URLEn code()但Facebook不呈现它。

It works for me, but I want to do it more efficiently.Is there any other way to escape such characters? I tried with Server.URLEncode() but Facebook doesn't render it.

在前进,
感谢
普里亚

Thanks in advance,
Priya

推荐答案

您应该使用 Uri.EscapeDataString如果你想有 RFC3986标准,其中百分号编码定义的兼容性的方法。

You should use the Uri.EscapeDataString method if you want to have compatibility with RFC3986 standard, where percent-encoding is defined.

例如空间始终将连接codeD为 20%人物:

For example spaces always will be encoded as %20 character:

var result = Uri.EscapeDataString("a q");
// result == "a%20q"

HttpUtility.UrlEn code 的用法示例(这是由内部使用 HttpServerUtility.UrlEn code的方式)返回 + 人物:

while for example usage of HttpUtility.UrlEncode (which is by the way internally used by HttpServerUtility.UrlEncode) returns + character:

var result = HttpUtility.UrlEncode("a q") 
// result == "a+q"

更重要的是,行为 Uri.EscapeDataString 与客户端兼容连接codeURIComponent JavaScript方法(除大小写,但RFC3986说,这是无关紧要的)。

What's more, the behavior of Uri.EscapeDataString is compatible with client side encodeURIComponent javascript method (except the case sensitivity, but RFC3986 says it is irrelevant).

这篇关于特殊字符编码比例在URL发送前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆