【发布时间】:2012-12-05 11:48:46
【问题描述】:
我需要从 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);
}
我是否从我的“假”上下文中遗漏了什么?如何添加?
【问题讨论】:
-
Send async e-mails的可能重复
-
@Dunc 我试图从没有可作为参数传递的 HttpContext 的 Windows 服务发送电子邮件,
-
好点,我最终直接使用 RazorEngine (razorengine.codeplex.com) - 两行代码来呈现模板,但没有脚手架 & 你必须自己发送电子邮件(仍然可以说比模拟更容易
HttpContext) -
如果你使用 Postal,你的伪装会起作用。我正在使用带有hangfire的Postal做同样的事情
标签: asp.net-mvc httpcontext mvcmailer