伪造MVC Mailer的HTTPContext

时间:2012-12-05 11:48:46

标签: asp.net-mvc httpcontext mvcmailer

我需要从asp.net MVC应用程序发送电子邮件,我正在使用MVC邮件程序来完成这项工作。只要有一个HTTPContext它就可以正常工作。不幸的是,我还需要发送没有上下文的电子邮件。

较新版本的MVC Mailer具有CurrentHttpContext的虚拟属性,当我使用“假”上下文设置它时,它似乎在本地工作。一旦它到达服务器,它将不再工作,并且失败并显示以下堆栈跟踪

System.ArgumentNullException: Value cannot be null.
Parameter name: httpContext
  at System.Web.HttpContextWrapper..ctor(HttpContext httpContext)
  at Glimpse.Core.Extensibility.GlimpseTimer.get_TimerMetadata()
  at Glimpse.Mvc3.Plumbing.GlimpseViewEngine.FindView(ControllerContext controllerContext, String viewName, String masterName, Boolean useCache)
  at System.Web.Mvc.ViewEngineCollection.<>c__DisplayClassc.<FindView>b__a(IViewEngine e)
  at System.Web.Mvc.ViewEngineCollection.Find(Func`2 lookup, Boolean trackSearchedPaths)
  at System.Web.Mvc.ViewEngineCollection.Find(Func`2 cacheLocator, Func`2 locator)
  at Mvc.Mailer.MailerBase.ViewExists(String viewName, String masterName)
  at Mvc.Mailer.MailerBase.PopulateBody(MailMessage mailMessage, String viewName, String masterName, Dictionary`2 linkedResources)
  at Mvc.Mailer.MailerBase.Populate(Action`1 action)

我做了一些研究,看来问题是找不到ViewEngineCollection,因为它在HTTPContext中寻找的东西。我返回的“假”上下文就像

一样简单
  public static HttpContextBase GetHttpContext(string baseUrl)
  {
      if (HttpContext.Current == null)
     {
    Log.InfoFormat("Creating a fake HTTPContext using URL: {0}", baseUrl);
    var request = new HttpRequest("/", baseUrl, "");
    var response = new HttpResponse(new StringWriter());
    return new HttpContextWrapper(new HttpContext(request, response));
      }

   return new HttpContextWrapper(HttpContext.Current);
  }

我错过了“假”背景中的某些内容吗?我该如何添加它?

1 个答案:

答案 0 :(得分:0)

你想模仿或伪造HttpContextBase和请求/响应。

如果您使用的是RhinoMocks,可以按照以下方式完成:

var httpResponse = MockRepository.GenerateMock<HttpResponseBase>();
var httpRequest = MockRepository.GenerateMock<HttpRequestBase>();
// you may need to stub specific methods of request/response
var context = MockRepository.GenerateMock<HttpContextBase>();
            context.Stub(r => r.Request).Return(httpRequest);
            context.Stub(r => r.Response).Return(httpResponse);

或者,如果您继承自 Base 类,则可以伪造。您在问题中传递给包装器的HttpContext将无效。