将部分视图渲染为字符串

时间:2013-05-05 06:18:16

标签: asp.net-mvc asp.net-mvc-3 razor partial-views

我知道这看起来像是一个重复的问题,但请在将其标记为重复之前阅读整个问题。

首先,我simulating the windows service in my ASP web application发送每周电子邮件,因此在Global.asax我正在运行我的功能,将发送电子邮件。

现在电子邮件内容是HTML格式,我想呈现视图以获取内容。问题是在我的功能中,我没有以下任何一项:

  • Controller
  • ControllerContext
  • HttpContext
  • RoutData
  • ...&多得多。这是有道理的,因为该函数作为回调被调用而不是作为HTTP请求动作。

我尝试使用RazorEngine将部分用作模板,然后使用Razor.Parse()方法读取文件。但是我从这种方法中遇到了很多问题,因为模板中没有包含任何内容。我的意思是:它一直告诉我当前上下文中不存在名称“Html”'CompiledRazorTemplates.Dynamic.becdccabecff' does not contain a definition for 'Html'即使我包含System.Web.Mvc.Html

我该如何解决这个问题?。

2 个答案:

答案 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();
   }
}