Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop HttpUtility.UrlEncode() from changing + to space?

Tags:

c#

asp.net

c#-4.0

I am using HttpUtility.UrlEncode() on a string token the original token is t+Bj/YpH6zE= when i HttpUtility.UrlDecode() it becomes t Bj/YpH6zE= which breaks the algorithm. is a way to stop changing + to a space in c#.

I am currently using replace method to achieve that var token_decrypt = HttpUtility.UrlDecode(token).Replace(" ", "+");

public HttpResponseMessage RegisterUser(User user, string token)
        {
            int accID;

            if(string.IsNullOrWhiteSpace(token))
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            else
            {
                try
                {
                     // token now = t Bj/YpH6zE= which will fail 
                     var token_decrypt = HttpUtility.UrlDecode(token);
                      token now = t Bj/YpH6zE= still the same 
                     accID = int.Parse(Crypto.Decrypt(token_decrypt, passPhrase));
                }
                catch
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid account ");
                }

her i encode the token

  string encoded_token = HttpUtility.UrlEncode(token);

            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
            msg.To.Add(mail);
            msg.From = new System.Net.Mail.MailAddress(from);

her is the call of RegisterUser from angular js

 RegistrationFactory.registerUser = function(user, token){
    return $http({method : "post", url:ConfigService.baseUrl+"User/RegisterUser?token="+token, data : user});
};
like image 211
MohamedAbbas Avatar asked Aug 04 '14 12:08

MohamedAbbas


1 Answers

No need to stop changing + to . If you use UrlEncode and UrlDecode correctly. Below code works as expected

var newtoken = HttpUtility.UrlEncode("t+Bj/YpH6zE=");
//newtoken is t%2bBj%2fYpH6zE%3d now
var orgtoken = HttpUtility.UrlDecode(newtoken);
//orgtoken: t+Bj/YpH6zE=

and for bonus

byte[] buf = Convert.FromBase64String(orgtoken);
like image 67
L.B Avatar answered Nov 16 '22 01:11

L.B