我正在尝试在我的测试类中对HttpContext进行单元测试,如下所示,但无法找到如何为此对象设置请求体的方法。
有什么办法吗?所以HttpContext.Current.Request.GetBufferedInputStream()
;将返回我设置的正文字符串的字节。
[TestMethod()]
public void GetRequestStringTest2()
{
string filename = "";
string url = "http://www.localhost.com";
string queryString = "";
HttpRequest request = new HttpRequest(filename, url, queryString);
// TODO: set request body here
// string requestBody = "request-test-123";
StringBuilder sb = new StringBuilder("response-test-123");
StringWriter writer = new StringWriter(sb);
HttpResponse response = new HttpResponse(writer);
HttpContext.Current = new HttpContext(request, response);
string requestString = HttpUtilities.GetRequestString();
Assert.IsNotNull(requestString);
Assert.AreEqual("request-test-123", requestString);
}
public static string GetRequestString()
{
if (HttpContext.Current != null)
{
Stream stream = HttpContext.Current.Request.GetBufferedInputStream();
new StreamReader(stream).ReadToEnd();
StreamReader bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
string requestString = bodyStream.ReadToEnd();
return requestString;
}
throw new InvalidOperationException("HttpContext.Current is not available.");
}
答案 0 :(得分:0)
有,但这并不容易。
为了做到这一点,你需要从HttpRequest调用方法internal void SetRawContent(HttpRawUploadedContent rawContent)
。
问题是,您无法从外部程序集调用内部方法,但有一些方法可以绕过此方法:C# - How to access internal class from external assembly。