我知道这看起来像是一个重复的问题,但请在将其标记为重复之前阅读整个问题。
首先,我simulating the windows service in my ASP web application发送每周电子邮件,因此在Global.asax
我正在运行我的功能,将发送电子邮件。
现在电子邮件内容是HTML格式,我想呈现视图以获取内容。问题是在我的功能中,我没有以下任何一项:
Controller
ControllerContext
HttpContext
RoutData
我尝试使用RazorEngine
将部分用作模板,然后使用Razor.Parse()
方法读取文件。但是我从这种方法中遇到了很多问题,因为模板中没有包含任何内容。我的意思是:它一直告诉我当前上下文中不存在名称“Html”或'CompiledRazorTemplates.Dynamic.becdccabecff' does not contain a definition for 'Html'
即使我包含System.Web.Mvc.Html
。
我该如何解决这个问题?。
答案 0 :(得分:1)
我认为最好的方法是假设您开发了一个真正的NT服务并使用HttpClient向您的部分视图发送http请求并以字符串形式接收响应并使用它来编写您的电子邮件。但是,您可以通过在HttpContext
类中进行一些更改,在RunScheduledTasks
方法中使用Scheduler
。
public delegate void Callback();
到
public delegate void Callback(HttpContext httpContext);
将cache.Current_HttpContext = HttpContext.Current;
添加到Run方法
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();
答案 1 :(得分:0)
不使用第三方库,可以使用此方法在Global.asax.cs文件中生成视图字符串
public class EmptyController : Controller { }
public string GetView(string viewName)
{
//Create an instance of empty controller
Controller controller = new EmptyController();
//Create an instance of Controller Context
var ControllerContext = new ControllerContext(Request.RequestContext, controller);
//Create a string writer
using (var sw = new StringWriter())
{
//get the master layout
var master = Request.IsAuthenticated ? "_InternalLayout" : "_ExternalLayout";
//Get the view result using context controller, partial view and the master layout
var viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, master);
//Crete the view context using the controller context, viewResult's view, string writer and ViewData and TempData
var viewContext = new ViewContext(ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
//Render the view in the string writer
viewResult.View.Render(viewContext, sw);
//release the view
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
//return the view stored in string writer as string
return sw.GetStringBuilder().ToString();
}
}