我需要從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