[英]can I use dynamic to redirect HttpContext.Current.Request?
I'm using RhinoMocks for testing. 我正在使用RhinoMocks进行测试。 It's not good at redirecting statics; 重定向静态变量并不擅长; I've considered using another library like the successor to Moles (edit: I guess the Fakes tool is only available in VS2012? that stinks) or TypeMock, but would prefer not to. 我曾经考虑过使用另一个库,例如Moles的后继库(编辑:我猜是Fakes工具仅在VS2012中可用,但很臭)或TypeMock,但不希望这样做。
I have a 3rd party library that takes in an HttpRequest object. 我有一个接受HttpRequest对象的第三方库。 My first stab at it was to use: 我的第一个方法是使用:
public void GetSamlResponseFromHttpPost(out XmlElement samlResponse,
out string relayState, HttpContextBase httpContext = null)
{
var wrapper = httpContext ?? new HttpContextWrapper(HttpContext.Current);
// signature of the next line cannot be changed
ServiceProvider.ReceiveSAMLResponseByHTTPPost(
wrapper.ApplicationInstance.Context.Request, out samlResponse, out relayState);
All looked fine, until I went to test it. 一切看起来不错,直到我去测试它。 The real issue here is that I need to stub out wrapper.ApplicationInstance.Context.Request
. 真正的问题是我需要将wrapper.ApplicationInstance.Context.Request
存根。 Which leads into a whole host of old school 'ASP.NET don't like testing' pain. 这导致了很多老派的“ ASP.NET不喜欢测试”的痛苦。
I have heard that you can use dynamic
magic in C# to redirect static methods. 我听说您可以在C#中使用dynamic
魔术来重定向静态方法。 Can't find any examples of doing this with something like HttpContext though. 但是找不到使用HttpContext这样的示例的任何示例。 Is this possible? 这可能吗?
Not an ideal solution, but my solution to test this was to use reflection and modify the object under the hood: 这不是一个理想的解决方案,但是我测试此问题的解决方案是使用反射并在后台修改对象:
httpRequest = new HttpRequest("default.aspx", "http://test.com", null);
var collection = httpRequest.Form;
// inject a value into the Form directly
var propInfo = collection.GetType().GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
propInfo.SetValue(collection, false, new object[] { });
collection["theFormField"] = val;
propInfo.SetValue(collection, true, new object[] { });
var appInstance = new HttpApplication();
var w = new StringWriter();
httpResponse = new HttpResponse(w);
httpContext = new HttpContext(httpRequest, httpResponse);
// set the http context on the app instance to a new value
var contextField = appInstance.GetType().GetField("_context", BindingFlags.Instance | BindingFlags.NonPublic);
contextField.SetValue(appInstance, httpContext);
Context.Stub(ctx => ctx.ApplicationInstance).Return(appInstance);
My goal here was to have wrapper.ApplicationInstance.Context.Request
return a form field value when asked. 我的目标是让wrapper.ApplicationInstance.Context.Request
在被询问时返回一个表单字段值。 It may have been roundabout, but it works. 它可能曾经是环形交叉路口,但是行得通。 This code only exists in test code so I'm happy with it. 该代码仅存在于测试代码中,因此我对此感到满意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.