如何阻止HttpUtility.UrlEncode()从+更改为空格?

时间:2014-08-04 12:10:14

标签: c# asp.net c#-4.0

我在字符串令牌上使用HttpUtility.UrlEncode()时原始令牌为t+Bj/YpH6zE=,当HttpUtility.UrlDecode()变为t Bj/YpH6zE=时会破坏算法。是一种停止在c#中将+更改为空格的方法。

我目前正在使用replace方法来实现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 ");
                }

她编码令牌

  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);

她是来自angular js的RegisterUser的调用

 RegistrationFactory.registerUser = function(user, token){
    return $http({method : "post", url:ConfigService.baseUrl+"User/RegisterUser?token="+token, data : user});
};

2 个答案:

答案 0 :(得分:5)

无需停止将+更改为。如果您正确使用UrlEncode和UrlDecode。下面的代码按预期工作

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

和奖金

byte[] buf = Convert.FromBase64String(orgtoken);

答案 1 :(得分:4)

您可以使用UrlPathEncode方法,UrlEncode方法的文档提到以下

  

您可以使用UrlEncode方法或UrlPathEncode方法对网址进行编码。但是,这些方法会返回不同的结果。 UrlEncode方法将每个空格字符转换为加号字符(+)。 UrlPathEncode方法将每个空格字符转换为字符串"%20",它表示十六进制表示法的空格。在对URL的路径部分进行编码时使用UrlPathEncode方法,以保证解码的URL一致,无论哪个平台或浏览器执行解码。

更多详情,请访问: http://msdn.microsoft.com/en-us/library/4fkewx0t(v=vs.110).aspx