2012-12-05 100 views
2

我需要从asp.net MVC应用程序发送电子邮件,并且使用MVC邮件程序来完成这项工作。只要有一个HTTPContext它工作正常。不幸的是,我还需要在没有上下文的情况下发送电子邮件。为MVC Mailer伪造一个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); 
    } 

我失去了从我的“假”方面的东西?我如何添加它?

+0

可能重复的[发送异步电子邮件](http://stackoverflow.com/questions/12201353/send-async-e-mails) – Dunc

+0

@Dunc我试图从一个Windows服务发送电子邮件,它doesn没有一个HttpContext可以作为参数传递, –

+0

好点,我最终直接使用RazorEngine代替(https://razorengine.codeplex.com) - 两行代码来渲染模板,但没有脚手架自己发送电子邮件(仍然可以比嘲笑'HttpContext'更容易) – Dunc

回答

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); 

,或者你可以假的,如果你的继承了基地类。你传入你的问题的包装HttpContext将无法正常工作。

+0

问题是,虽然我伪装它,它仍然需要能够与助手等工作。 –

+0

看得更近,你也会遇到麻烦试图使用系统.Web.Mvc.ViewEngineCollection没有马特什么的假。 – dove

+0

这正是我碰到的问题。任何建议的方法呢? –