我認爲最好的方法是假設你開發了一個真正的NT服務,並使用HttpClient發送一個http請求到你的局部視圖,並以字符串的形式接收響應並用它來組成你的電子郵件。但是,通過在Scheduler
類中進行一些更改,您可以在RunScheduledTasks
方法中使用HttpContext
。
public delegate void Callback();
到
public delegate void Callback(HttpContext httpContext);
添加cache.Current_HttpContext = HttpContext.Current;
到運行方法
public static void Run(string name, int minutes, Callback callbackMethod)
{
_numberOfMinutes = minutes;
CacheItem cache = new CacheItem();
cache.Name = name;
cache.Callback = callbackMethod;
cache.Cache = HttpRuntime.Cache;
cache.LastRun = DateTime.Now;
cache.Current_HttpContext = HttpContext.Current;
AddCacheObject(cache);
}
變化CacheCallback
到
private static void CacheCallback(string key, object value, CacheItemRemovedReason reason)
{
CacheItem obj_cache = (CacheItem)value;
if (obj_cache.LastRun < DateTime.Now)
{
if (obj_cache.Callback != null)
{
obj_cache.Callback.Invoke(obj_cache.Current_HttpContext);
}
obj_cache.LastRun = DateTime.Now;
}
AddCacheObject(obj_cache);
}
編輯: 如何使用HttpClient
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://localhost/controller/action/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
剃刀引擎需要的HttpContext,viewcontext解析視圖文件。您可以將帶有標記的HTML電子郵件模板放在單獨的文件中,然後在預定的任務中使用它來準備最終的電子郵件。 – eka 2013-05-05 07:19:45