Tuesday, 4 March 2014

How to Pass Encoded data in Query String in C# ASP.NET

Solution :-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class encode
{
    public encode()
    {

    }
    public string base64Encode(string data)
    {
        try
        {
            byte[] encData = new byte[data.Length];
            encData = System.Text.Encoding.UTF8.GetBytes(data);
            string encodedData = Convert.ToBase64String(encData);
            return encodedData;
        }
        catch (Exception ex)
        {
            throw new Exception("Error in base64Encode" + ex.Message);
        }
    }
    public string base64Decode(string data)
    {
        try
        {
            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            System.Text.Decoder utf8Decode = encoder.GetDecoder();

            byte[] todecode = Convert.FromBase64String(data);
            int charCount = utf8Decode.GetCharCount(todecode, 0, todecode.Length);
            char[] decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode, 0, todecode.Length, decoded_char, 0);
            string result = new String(decoded_char);
            return result;
        }
        catch (Exception ex)
        {
            throw new Exception("Error in base64Decode" + ex.Message);
        }
    }
}
Just Create a class like this..Now call one of these method by just passing any string data, it will also return string data after encode/decode. Now you can pass this data in your query string just like any normal data.Now the question which was raised on our mind, What is base64 Encoding??

It's a textual encoding of binary data where the resultant text has nothing but letters, numbers and the symbols "+", "/" and "=". It's a convenient way to store/transmit binary data over media that is specifically used for textual data.


That’s it!!…..Happy Programming...

No comments:

Post a Comment