简体   繁体   中英

Returning an HttpResponseMessage with a batch response

I've got a unit test which I'm trying to fix. All I need to do is return a valid 200 HttpResponseMessage with a batch response for a single query (A 404 will do). I'm new to OData and dealing with HTTPMessages in general. This is what I've done so far, but I'm not sure it's the right way to do things. Could you help me understand where I might be going wrong?

            string content = string.Format(
                @"--batch_{0}
Content-Type: application/http
Content-Transfer-Encoding: binary
HTTP/1.1 404 Not Found
OData-Version: 4.0
Content-Type: application/json;odata.metadata=minimal;odata.streaming=true;charset=utf-8
Content-Length: 42",
batchCode);

            content = content + Environment.NewLine + @"{ .error.:.not_found.,.reason.:.missing.}".
            content = content + Environment.NewLine + Environment.NewLine + string.Format(@"--batch_{0}--", batchCode) + Environment.NewLine;

            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(content, System.Text.Encoding.UTF8, "multipart/mixed")
            };
  1. Since this is the response the boundary must be: --batchresponse_{batchCode} .
  2. You don't need to specify the OData-Version in the sub-responses, only in the header of the parent.
  3. There needs to be a newline between the headers and the body (in your case before the HTTP/1.1 404 Not Found line).
  4. There must be a newline between the headers and the body of the child-response (before the line w/ your json).

A complete response body may look something like this:

--batchresponse_4a21740c-169a-4442-b771-8989207e80e9
Content-Type: application/http
Content-Transfer-Encoding: binary

HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8

{"Some":"Json"}
--batchresponse_4a21740c-169a-4442-b771-8989207e80e9--

Also, the json in the response doesn't look like valid json to me, not sure if that's a problem.

        string batchCode = this.GetBatchCode(requestContent);
        var innerResponse = new HttpMessageContent(new HttpResponseMessage(HttpStatusCode.NotFound));

        MultipartContent batchContent = new MultipartContent("mixed", "batch_" + batchCode);

        innerResponse.Headers.Remove("Content-Type");
        innerResponse.Headers.Add("Content-Type", "application/http");
        innerResponse.Headers.Add("Content-Transfer-Encoding", "binary");

        batchContent.Add(innerResponse);

        var outerResponse = new HttpResponseMessage(HttpStatusCode.OK);
        outerResponse.Content = batchContent;

        return outerResponse;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM