I need to send out emails from an asp.net MVC application and I am using MVC mailer to do the job. As long as there is an HTTPContext it works fine. Unfortunately, I also need to send out emails where there is no context.
The newer version of MVC Mailer has a virtual property for CurrentHttpContext and when I set that with a "fake" context it seems to work locally. As soon as it reaches the server it won't work any more and fails with the following stack trace
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)
I've done some research and it appears that the problem is that the ViewEngineCollection can't be found because of something it is looking for in the HTTPContext. The "fake" context I am returning is as simple as
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);
}
Am I missing something from my "fake" context? How do I add it?