Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL Encode all non alpha numeric in C#

I need to fully URL Encode an email address.

HttpUtility.UrlEncode seems to ignore certain characters such as ! and .

I need to pass an email address in a url formated like this:

/Users/[email protected]/Comments

Because my WebMethod uri template looks like this:

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

The period breaks WCF and will not pass the email address to my REST webservice method. Removing the period passes the value just fine. I'm hoping there is a method which will encode all non alpha numeric characters since everything consuming this service will need to do this.

EDIT

I had considered using:

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

Do most other languages have easy ways to convert a string to base64? My main concern is that our customers who consume this service will need to encode the email address using Java, PHP, Ruby, etc.

like image 895
Vyrotek Avatar asked Jun 18 '10 19:06

Vyrotek


1 Answers

Here's a potential Regex you could use to accomplish the encoding.

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

I'm not sure that there is an existing framework method defined to strictly encode all non-alphanumeric characters that you could point your clients to.

like image 173
Michael Petito Avatar answered Oct 16 '22 07:10

Michael Petito