在QueueBackgroundWorkItem中将视图渲染为字符串不起作用

时间:2016-11-02 21:53:28

标签: c# asp.net-mvc-5

所以我有一个渲染视图并将其保存为字符串的方法:

public class HtmlFactory
{
    private DetailsController controller = ViewRenderer.CreateController<DetailsController>();

    public string writeAbout(contextDB db)
    {
        string str = "";
        var model = VMF.GetAboutViewModel(true, db);
        str = RenderPartialViewToString(controller, "~/Areas/ControlCenter/Views/Details/About.cshtml", model);
        return str;
    }

    private string RenderPartialViewToString(Controller controller, string viewName, object model)
    {
        controller.ViewData.Model = model;

        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, "~/Areas/ControlCenter/Views/Shared/_Layout.cshtml");

            var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
            try
            {
                viewResult.View.Render(viewContext, sw);
            }
            catch (Exception e)
            {
                // errors caught here
                Console.Write(e.StackTrace);
            }

            return sw.ToString();
        }
    }
}

当我从MVC动作中调用HtmlFactory.writeAbout()时,一切正常:

public class MyController : Controller
{
    public void writeIt()
    {
        var HF = new HtmlFactory();
        HF.writeAbout(db);
    }
}

但是当我尝试将其作为后台任务调用时,我收到错误:

    public void writeIt()
    {
        var HF = new HtmlFactory();
        HostingEnvironment.QueueBackgroundWorkItem(ct => HF.writeAbout(db));
    }

我在此行中收到错误:viewResult.View.Render(viewContext, sw);。 错误:

  

价值不在预期范围内。

这是堆栈跟踪:

  

at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode,IntPtr errorInfo)

     

at System.Web.Hosting.IIS7WorkerRequest.GetServerVariableInternal(String name)

     

at System.Web.Hosting.IIS7WorkerRequest.GetServerVariable(String name)

     

at System.Web.Hosting.IIS7WorkerRequest.GetRemoteAddress()

     

在System.Web.HttpWorkerRequest.IsLocal()

     

在System.Web.HttpRequestWrapper.get_IsLocal()

     

在System.Web.WebPages.WebPageBase.ExecutePageHierarchy()

     

在System.Web.Mvc.WebViewPage.ExecutePageHierarchy()

     

在System.Web.WebPages.StartPage.RunPage()

     

在System.Web.WebPages.StartPage.ExecutePageHierarchy()

     

在System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext,TextWriter writer,WebPageRenderingBase startPage)

     

在System.Web.Mvc.RazorView.RenderView(ViewContext viewContext,TextWriter writer,Object instance)

     

在System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext,TextWriter writer)

     

at mySite.Factories.HtmlFactory.RenderPartialViewToString(Controller controller,String viewName,Object model)

如何使其作为后台操作?

0 个答案:

没有答案