Faking an HTTPContext for MVC Mailer



我需要从 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);
  }

我是否从我的"假"上下文中遗漏了什么?如何添加?

你想模拟或伪造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);

或者,如果您从类继承,则可以伪造。 您在问题中传递到包装器的 HttpContext 将不起作用。

最新更新