10

有一个简单的 C# 单元测试:

[TestMethod]
public void JsonPostTest()
{
  string testUri1 = "http://localhost:1293/Test/StreamDebug";
  string testUri2 = "http://localhost:1293/Test/StreamDebug2?someParameter=abc";

  string sampleJson = @"
  {
    ""ID"": 663941764,
    ""MessageID"": ""067eb623-7580-4d82-bb5c-f5d7dfa69b1e""
  }";

  HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(testUri1);
  EmailConfig config = GetTestConfigLive();

  // Add postmark headers
  request.Accept = "application/json";
  request.ContentType = "application/json";

  request.Method = "POST";
  using (var outStream = new StreamWriter(request.GetRequestStream()))
  {
    outStream.Write(sampleJson);
  }

  // Get response
  HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  string resultText = "";
  using (var reader = new StreamReader(response.GetResponseStream()))
  {
    resultText = reader.ReadToEnd();
  }

  Assert.Inconclusive();
}

以及一组简单的 MVC 操作,用于使用并将发布的数据回显到单元测试(请注意,两个操作中的代码是相同的):

[HttpPost]
[ValidateInput(false)]
public ActionResult StreamDebug()
{
  string postbody = "";
  using (StreamReader reader = new StreamReader(Request.InputStream, Encoding.UTF8))
  {
    postbody = reader.ReadToEnd();
  }
  return this.Content(postbody);
}

[HttpPost]
[ValidateInput(false)]
public ActionResult StreamDebug2(string someParameter)
{
  string postbody = "";
  using (StreamReader reader = new StreamReader(Request.InputStream, Encoding.UTF8))
  {
    postbody = reader.ReadToEnd();
  }
  return this.Content(postbody);
}

如果我发布到第一个操作,我会得到一个包含发布的 json 的字符串,如果我发布到第二个操作,我会得到一个空字符串。

为了使事情更有趣,如果我将单元测试中的内容类型更改为“text/plain”,则两个操作都会返回预期值。

谁能解释为什么会发生这种情况?

还值得注意的是,这两种情况下两个操作的请求长度似乎都是正确的长度。

更多环境信息:单元测试在一个单独的 MS 测试项目中。动作在一个空的 MVC 4.0 项目 (Net 4.0) 中。

4

1 回答 1

13

请求管道中的某处可能Request.InputStream已被读取。在这种情况下,它的位置已经在末尾,当然ReadToEnd什么也不读取并返回空字符串。这是我们案例中问题的根源。重置位置可以解决问题:

[HttpPost]
[ValidateInput(false)]
public ActionResult StreamDebug2(string someParameter)
{
  string postbody = "";
  Request.InputStream.Position = 0;
  using (StreamReader reader = new StreamReader(Request.InputStream, Encoding.UTF8))
  {
    postbody = reader.ReadToEnd();
  }
  return this.Content(postbody);
}

更新。经过一点点挖掘资源后,我也发现了位置发生变化的原因。事实证明,Request.InputStream它的使用JsonValueProviderFactory方式如下:

// System.Web.Mvc.JsonValueProviderFactory
private static object GetDeserializedObject(ControllerContext controllerContext)
{
    if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
    {
        return null;
    }
    StreamReader streamReader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
    string text = streamReader.ReadToEnd();
    if (string.IsNullOrEmpty(text))
    {
        return null;
    }
    JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
    return javaScriptSerializer.DeserializeObject(text);
}

调用此方法ControllerActionInvoker以从请求中检索值并将它们绑定到操作参数。Request.InputStream请注意,这是通过所有 MVC 使用的唯一地方。

因此,如果请求的内容类型是 json,则调用上述方法,输入流被转移并尝试再次读取它而不重置位置失败。但是,当内容类型是纯文本时,MVC 不会尝试使用 json 反序列化来读取请求,在控制器中调用之前不会读取输入流,并且一切都按预期工作。

于 2013-06-26T12:29:44.687 回答