I'm trying to write a javascript OData consumer that will take several of my entities at once for a POST (so I can submit an entity and associated children at once) to my WebApi server. However I get an annoying error:
ExceptionMessage: "The message header 'POST /odata/MyEntity HTTP/1.1' is invalid. The header value must be of the format '<header name>: <header value>'."
ExceptionType: "Microsoft.Data.OData.ODataException"
Message: "An error has occurred."
StackTrace: " at Microsoft.Data.OData.ODataBatchReaderStream.ValidateHeaderLine(String headerLine, String& headerName, String& headerValue)
↵ at Microsoft.Data.OData.ODataBatchReaderStream.ReadHeaders()
↵ at Microsoft.Data.OData.ODataBatchReaderStream.ProcessPartHeader()
↵ at Microsoft.Data.OData.ODataBatchReader.SkipToNextPartAndReadHeaders()
↵ at Microsoft.Data.OData.ODataBatchReader.ReadImplementation()
↵ at Microsoft.Data.OData.ODataBatchReader.ReadSynchronously()
↵ at Microsoft.Data.OData.ODataBatchReader.InterceptException[T](Func`1 action)
↵ at Microsoft.Data.OData.ODataBatchReader.Read()
↵ at System.Web.Http.OData.Batch.DefaultODataBatchHandler.<ParseBatchRequestsAsync>d__e.MoveNext()
↵--- End of stack trace from previous location where exception was thrown ---
↵ at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
↵ at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
↵ at System.Web.Http.OData.Batch.DefaultODataBatchHandler.<ProcessBatchAsync>d__0.MoveNext()
↵--- End of stack trace from previous location where exception was thrown ---
↵ at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
↵ at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
↵ at System.Web.Http.Batch.HttpBatchHandler.<SendAsync>d__0.MoveNext()"
My function to build this is as follows:
var oReq = new XMLHttpRequest();
oReq.onload = function () {
if (oReq.status == 404) {
defer.reject(oReq.statusText);
} else {
var response = JSON.parse(oReq.response);
if (response['odata.error']) {
defer.reject(oReq['odata.error']);
} else if (response.Message) {
defer.reject(response.Message);
} else {
defer.resolve(response);
}
}
};
oReq.onerror = function () {
defer.reject(oReq.statusText);
};
oReq.open("POST", "/odata/$batch", true);
var batch = "batch_" + newGuid();
oReq.setRequestHeader("Content-type", 'multipart/mixed; boundary="' + batch + '"');
var body = "--" + batch + "\r\n";
ko.utils.arrayForEach(entities, function (entity) {
body = body + [
'Content-Type: application/http; msgtype=request',
'',
'POST ' + url + ' HTTP/1.1',
'Content-Type: application/json; charset=utf-8',
'',
ko.toJSON(entity),
"--" + batch
].join('\r\n')
});
oReq.send(body + "--");
Have I not formatted the request properly? I've been trying to emulate this:
Thanks.