2010-06-18 70 views
7

我需要完整的URL编码一个电子邮件地址。URL在C#中编码所有非字母数字#

HttpUtility.UrlEncode似乎忽略某些字符,如!和。

我需要在格式化这样的URL传递的电子邮件地址:

/Users/[email protected]/Comments 

因为我的WebMethod URI模板看起来是这样的:

[WebGet(UriTemplate = "Users/{emailAddress}/Comments")] 

期间休息WCF并不会通过电子邮件地址到我的REST webservice方法。 删除期限通过值就好了。我希望有一种方法将编码所有非字母数字字符,因为所有使用此服务的人都需要这样做。

编辑

我一直在使用考虑:

Convert.ToBase64String(Encoding.ASCII.GetBytes("[email protected]")) 

大多数其他语言有简便的方法来将字符串转换为Base64?我最关心的是,我们的客户谁消费这项服务将需要编码使用Java,PHP和Ruby等

+0

重新格式化了一下。 – Femaref 2010-06-18 19:11:33

+0

你得到了什么样的错误? – 2010-06-18 19:38:36

+0

A 404 Not Found – Vyrotek 2010-06-18 19:45:35

回答

0

我发现了这个问题的解决方案。

.net 4.0实际上解决了URI模板中特殊字符的问题。

此线程指出我在正确的方向。 http://social.msdn.microsoft.com/Forums/en/dataservices/thread/b5a14fc9-3975-4a7f-bdaa-b97b8f26212b

我添加了所有的配置设置和它的工作。但请注意,它只能与.Net 4.0的REAL IIS设置一起使用。我似乎无法让它与Visual Studio Dev IIS一起工作。

更新 - 其实,我试着删除那些配置设置,它仍然有效。这可能是.Net 4.0默认解决了这个问题。

0

使用十六进制的电子邮件地址。有一个的ConvertTo和从进行了抽样检测...

你也可以只花葶不使用正则表达式让你的URL看起来还是蛮符合A到Z的字符。

它将返回号码的大名单,所以你应该是不错的

 public static string ConvertToHex(string asciiString) 
    { 
     var hex = ""; 
     foreach (var c in asciiString) 
     { 
      int tmp = c; 
      hex += String.Format("{0:x2}", Convert.ToUInt32(tmp.ToString())); 
     } 
     return hex; 
    } 

    public static string ConvertToString(string hex) 
    { 
     var stringValue = ""; 
     // While there's still something to convert in the hex string 
     while (hex.Length > 0) 
     { 
      stringValue += Convert.ToChar(Convert.ToUInt32(hex.Substring(0, 2), 16)).ToString(); 
      // Remove from the hex object the converted value 
      hex = hex.Substring(2, hex.Length - 2); 
     } 

     return stringValue; 
    } 

    static void Main(string[] args) 
    { 
     string hex = ConvertToHex("[email protected]"); 
     Console.WriteLine(hex); 
     Console.ReadLine(); 
     string stringValue = 
     ConvertToString(hex); 
     Console.WriteLine(stringValue); 
     Console.ReadLine(); 

    } 
2

这里是你可以用它来完成编码一个潜在的正则表达式。

Regex.Replace(s, @"[^\w]", m => "%" + ((int)m.Value[0]).ToString("X2"));

我不知道有规定严格编码,你可以点你的客户所有非字母数字字符的现有框架的方法。

0

除非我弄错了,URL编码是简单百分号后跟ASCII数字(十六进制),所以这应该工作...

Dim Encoded as New StringBuilder() 

For Each Ch as Char In "[email protected]" 
    If Char.IsLetterOrDigit(Ch) 
     Encoded.Append(Ch) 
    Else 
     Encoded.Append("%") 
     Dim Byt as Byte = Encoding.ASCII.GetBytes(Ch)(0) 
     Encoded.AppendFormat("{0:x2}", Byt) 
    End If 
Next 

上面的代码导致something%2Bme%40example.com

+0

对不起,我使用VB.NET,但你可以很容易地改变:http://codechanger.com/ – 2010-06-18 19:51:37

+0

你会如何解码? – Vyrotek 2010-06-18 21:05:53

+0

@Vyrotek你可以依靠'Uri.UnescapeDataString()'。 – 2010-06-18 21:24:35

相关问题