Moons
Moons

Reputation: 3854

Pass Byte Array that was in Session object to a Web Service (Asp.Net 2.0 asmx) through a JSON object

I have a code:

Session["timestamp"] has a byte array in it coming using LInq to Entity

Now when i call this function it throws an error

The web service has a signature like:

[WebMethod]
public  string IsRowChanged(int en_id , byte[] timestamp)
{
}

If I replace byte[] with string everywhere it works.

$.ajax({
    type: "POST",
    url: "UpdateEntityService.asmx/IsRowChanged",
    data: "{ 'en_id':'" + '<%= Request.QueryString["entity_id"] == null ? "1" : Request.QueryString["entity_id"] %>' + "' , 'timestamp': '" + '<%= (Session["timestamp"]) %>' + "'   }",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {

        var result = msg.d;

        if (result == "0") {

            save_valid();

            $.prompt("Data Saved Sucessfully");

        }
        else {

            $.prompt("Data Concurrency Error! Reload the Page.. by pressing F5");

        }

    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert(textStatus);
        alert(textStatus);
        alert(errorThrown);
    }
});

Any help is appreciated.

Upvotes: 3

Views: 8055

Answers (2)

codeandcloud
codeandcloud

Reputation: 55220

Try this. Pass it as string and convert it to ByteArray inside the function

[WebMethod]
public  string IsRowChanged(int en_id , string ts)
{
    byte[] timestamp = Encoding.UTF8.GetBytes(ts);
    // rest of your function here
}

And if you don't know the encoding type, use this function

private byte[] ConvertStringToBytes(string input)
{
    MemoryStream stream = new MemoryStream();

    using (StreamWriter writer = new StreamWriter(stream))
    {
        writer.Write(input);
        writer.Flush();
    }

    return stream.ToArray();
}

Namespace used : using System.IO;

The point is, whichever encoding you are using, use the same decoding method to retrieve it. Here is an example for ASCII encoding / decoding

At your page encode like this.

string value = ASCIIEncoding.ASCII.GetString(temp_array);
HttpContext.Current.Session["timestamp"] = value;

Now at ASMX decode like this.

[WebMethod]
public  string IsRowChanged(int en_id , string ts)
{
    byte[] timestamp = Encoding.ASCII.GetBytes(ts);
    // rest of your function here
}

Upvotes: 4

sra
sra

Reputation: 23973

You should Base encode binary data and convert it back to byte[] at serverside.

// returns a byte[]
System.Convert.FromBase64String(base64String);
// returns a string
System.Convert.ToBase64String(byteData);

Upvotes: 5

Related Questions