有一个简单的 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) 中。