1. 程式人生 > >C#實現HttpUtility.UrlEncode輸出大寫字母

C#實現HttpUtility.UrlEncode輸出大寫字母

在C#中,將字串app=97b0c5c6-3986-404b-94ad-e5394316c3e1&info={"OrderNo":"SN180728932848","Amount":10.0}&notify_url=http://pay2.ybdemo.com/Notify/TokenPay_Notify&payment_amount=10.000000000000000&payment_type=1
用HttpUtility.UrlEncode()編碼結果為app=97b0c5c6-3986-404b-94ad-e5394316c3e1&info=%7b%22OrderNo%22%3a%22SN180728932858%22%2c%22Amount%22%3a10.0%7d&notify_url=http%3a%2f%2fpay2.ybdemo.com%2fNotify%2fTokenPay_Notify&payment_amount=10.000000000000000&payment_type=1, 但是接收方需要的是app=97b0c5c6-3986-404b-94ad-e5394316c3e1&info=%7B%22OrderNo%22:%22SN180728932848%22%2C%22Amount%22:10.0%7D&notify_url=http:%2F%2Fpay2.ybdemo.com%2FNotify%2FTokenPay_Notify&payment_amount=10.000000000000000&payment_type=1
一開始看到這需求,我的注意力就轉移到怎麼將%7b轉為%7B,正則等方法馬上浮現出來,最後發現,一開始思路就錯了,捨本逐末,用HttpUtility.UrlEncode就可以搞定:

public string UrlEncode(string str)
{
    StringBuilder builder = new StringBuilder();
    foreach (char c in str)
    {
        if (HttpUtility.UrlEncode(c.ToString()).Length > 1)
        {
            builder.Append(HttpUtility.UrlEncode(c.ToString()).ToUpper());
        }
        else
        {
            builder.Append(c);
        }
    }
    return builder.ToString();
}

在python中 好像:不會被編碼為%3A,所以還得還原 return builder.ToString().Replace("%3A",":");