I am try to return a custom object from VB.NET code behind to a AngularJS HTTP Post. Based on the user requests, this object could be very large. Very, very large. Whenever that happened, I got a OutOfMemoryException when trying to serialize it. Therefore, I am now using the JSON.NET package from Newtonsoft to serialze it using a StringWriter:
Using sw As New StringWriter()
Using writer As JsonWriter = New JsonTextWriter(sw)
Dim serializer As New JsonSerializer()
serializer.Serialize(writer, periodData)
writer.Flush()
End Using
End Using
While this works, when I then try to do sw.ToString I still get that OutOfMemoryException.
So, I trawled through the internet and I believe I can use a StreamWriter sent to a HttpResponse object and then flush the response to return it to the web client call. However, I cannot figure out how to do this.
Any help? Or if I am way off track, give me a better way to do this?
Update 1
Apparently, I cannot use HttpResponse in a Using statement because I get a "using operand must implement system.idisposable" error. So now I am having trouble creating an HttpResponse object in the WebMethod. Passing both TextWriter and HttpWriter as params for the constructor give me errors.
Update 2
Okay, so I am no longer getting an OutOfMemoryException when trying to serialize the object. However, I believe I am doing something wrong since my StreamWriter doesn't seem to be writing to the HttpResponse Object. This is my current code:
Dim response As HttpResponse = HttpContext.Current.Response()
response.ContentType = "application/json"
response.Clear()
response.BufferOutput = True
Using sw As New StreamWriter(response.OutputStream, System.Text.Encoding.UTF8)
Using writer As JsonWriter = New JsonTextWriter(sw)
Dim serializer As New JsonSerializer()
serializer.Serialize(writer, periodData)
writer.Flush()
End Using
sw.Flush()
End Using
response.Flush()
Then when I pause my JavaScript in the Chrome developer console, the response object is just an empty string. The javascript is just a basic Angular $http.post call:
$http.post('url.aspx/GetData', angular.toJson({
param1: data1,
param2: data2,
param3: data3
})).then(function (response) {
//Do stuff with response which is currently an empty string.
}
I don't believe my VB.NET code is correct. Help?