我需要从 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);
}
我是否从我的“假”上下文中遗漏了什么?我该如何添加它?