Sending/Receiving byte[] With AJAX and ASP.NET MVC
Overview: Here is an summed up description of what I'm doing - I have a C# application that's running constantly that contains a HTTPListener and waits for a request. Then there is a MVC Web Application where on one of the pages is a button that fires some JS that does an ajax post to the address that the HTTP Listener is listening on, when that button is clicked, the listener catches this request then the C# application performs some other job (not relevant to the problem) and then produces a byte array. This byte array is then sent back as part of the response to the original request, and so the success
function of the ajax post that made the request is triggered with the byte array in the success function's data parameter. Now another ajax post is made, but this time to a MVC controller so that the byte array can be saved in my db:
Here is some code.
First, Here is the ajax post that makes the request to the HTTP Listener, the data passed along with the post is just some metadata that I use (for now ignore the code in the success function):
$.ajax({
type: "POST",
url: 'http://127.0.0.1:8089/',
data: '{ "Action":"Enroll", "RefUser":"6" }',
crossDomain: true,
success: function (data) {
//Code that posts array to server to be saved in DB
}); //end of ajax
And here is the HTTP Listener's callback method that catches the request and sends the response:
var context = listener.EndGetContext(listenerresult);
Thread.Sleep(1000);
var data_text = new StreamReader(context.Request.InputStream,context.Request.ContentEncoding).ReadToEnd();
//functions used to decode json encoded data.
JavaScriptSerializer js = new JavaScriptSerializer();
RequestConfiguration RequestConfig = (RequestConfiguration)js.Deserialize(data_text, typeof(RequestConfiguration));
byte[] templateDataArray = null;
//Do some work and assign value to the byte array, 'templateDataArray'
//I append a status code and a message to the array of bytes and send everthing back as a response
//The values are split using the '<>' characters.
byte[] msgDataArray = System.Text.Encoding.UTF8.GetBytes("1<>Success" + "<>");
byte[] responseArray = new byte[msgDataArray.Length + templateDataArray.Length];
msgDataArray.CopyTo(responseArray, 0);
templateDataArray.CopyTo(responseArray,msgDataArray.Length);
var response = context.Response;
response.ContentLength64 = responseArray.Length;
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Access-Control-Allow-Methods", "POST, GET");
response.StatusCode = 200;
response.StatusDescription = "OK";
response.OutputStream.Write(responseArray, 0, responseArray.Length);
response.OutputStream.Close();
Looking now at the success function from the original ajax post:
...
success: function (data) {
//Code that posts array to server to be saved in DB
var returnArray = data.split("<>");
if (returnArray[0] === "1") {
alert(returnArray[1]);
$("#Loader").addClass('hide');
$.ajax({
type: "POST",
url: '@Url.Action("EnrollFingerprintToDB")',
dataType: 'json',
data: { enrollData: NewID + '<>' + returnArray[2] },
success: function (data) {
alert(data.msg);
}
});//end of inner ajax
} //end of if
} //end of success
...
When I do a sample run, here is what I get back in the success function, lets look at the data after it has been split (the var 'returnArray'):
Note that we now post returnArray[2]
to the MVC controller, which contains the byte array (encoded as a string right now). Here is the mvc controller that catches that post:
[HttpPost]
public ActionResult EnrollFingerprintToDB(string enrollData)
{
string[] sDataParts = enrollData.Split(new[] { "<>" }, StringSplitOptions.None);
var bytes = System.Text.Encoding.UTF8.GetBytes(sDataParts[1]);
if (FingerprintBLL.InsertFingerprintTemplate(int.Parse(sDataParts[0]),bytes))
{
return Json(new { success = true, msg = "Template successfully saved" });
}
else
{
return Json(new { success = true, msg = "Template could not be saved" });
}
}
What concerns me and what my question is
Why is the array that I send off from the listener different from the one I finally read in the MVC controller? The reason I say that is, Here is the byte array sent from the Listener:
And here is the array the is received at the MVC controller:
As you can see the MVC Controller Action takes in a string that is split into two and the second part is converted to a byte array, and that second part is the byte array in string form received from the listener (take another look at that second ajax post and you'll see it).
I Believe that I'm taking the incorrect approach to send and receive byte data.
链接地址: http://www.djcxy.com/p/6678.html