我需要从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);
}
我失去了从我的“假”方面的东西?我如何添加它?
可能重复的[发送异步电子邮件](http://stackoverflow.com/questions/12201353/send-async-e-mails) – Dunc
@Dunc我试图从一个Windows服务发送电子邮件,它doesn没有一个HttpContext可以作为参数传递, –
好点,我最终直接使用RazorEngine代替(https://razorengine.codeplex.com) - 两行代码来渲染模板,但没有脚手架自己发送电子邮件(仍然可以比嘲笑'HttpContext'更容易) – Dunc