返回带有批处理响应的HttpResponseMessage

时间:2019-03-01 23:16:33

标签: c# http odata

我有一个要修复的单元测试。我需要做的就是返回一个有效的200 HttpResponseMessage,并带有针对单个查询的批处理响应(A 404会这样做)。我是OData的新手,通常会处理HTTPMessages。到目前为止,这是我所做的事情,但是我不确定这是做事的正确方法。你能帮我了解我可能会出问题的地方吗?

            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")
            };

2 个答案:

答案 0 :(得分:0)

  1. 由于这是响应,因此边界必须为:--batchresponse_{batchCode}
  2. 您无需在子响应中指定OData-Version,只需在父响应的标题中指定即可。
  3. 标题和正文之间需要有一个换行符(在您的情况下,在HTTP/1.1 404 Not Found行之前)。
  4. 标题和子响应正文之间必须有换行符(在带有json的行之前)。

完整的响应主体可能看起来像这样:

--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--

另外,响应中的json对我来说似乎不是有效的json,不确定是否有问题。

答案 1 :(得分:0)

        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;