単体テストの目的で模擬リクエストを実行するためのこのコードを見つけました。ユーザーホストアドレスを設定しようとしていますが、このコードで概説されているのと同じ方法を使用してそれを達成する方法が明確ではありません。ヘッダーの設定が許可されていないことがわかったので、リフレクションを通じて行う必要があると考えています。これを達成する方法はありますか?
public static HttpContext FakeHttpContext()
{
var httpRequest = new HttpRequest("", "http://fakurl/", "");
var stringWriter = new StringWriter();
var httpResponse = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponse);
var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
new HttpStaticObjectsCollection(), 10, true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc, false);
httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null, CallingConventions.Standard,
new[] { typeof(HttpSessionStateContainer) },
null)
.Invoke(new object[] { sessionContainer });
httpContext.Request.Headers["REMOTE_ADDR"] = "XXX.XXX.XXX.XXX"; // not allowed
return httpContext;
}
このモックライブラリも試しました:
https://gist.github.com/rally25rs/1578697
ユーザーのホストアドレスはまだ読み取り専用です。