Cannot use MvcHtmlString/IHtmlString with RazorEngine

走远了吗. 提交于 2019-12-12 13:16:45

问题


I just started playing around with the RazorEngine and I'm stumbling when using a static helper method. It just produces an MvcHtmlString/IHtmlString for the template. When calling Razor.Parse(...) I get

RazorEngine.Templating.TemplateCompilationException : Unable to compile template. 
Der Typ 'System.Web.IHtmlString' ist in einer nicht referenzierten Assembly definiert. (not referenced)
Fügen Sie einen Verweis auf die Assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' hinzu.

I have added references to System.Web, System.Web.Mvc, System.Web.WebPages. Also tried to add them to the cshtml (@using System.Web, @using System.Web.Mvc). But @using System.Web.Mvc results in .Mvc is not available in System.Web?!

I'm trying to build the templates in NUnit Tests currently.


回答1:


The RazorEngine has a class CompilerServicesUtility. This is responsible for loading and making assemblies available when your view is compiled. It by default returns all assemblies loaded in the current AppDomain.

Its bit unintuitive for someone looking at the code, but one way to make sure that your Razor view compiles and you can use MvcHtmlString is to load the System.Web and System.Web.Mvc assemblies into the current AppDomain using AppDomain.Current.Load("") prior to executing/ compiling your view.




回答2:


An old question. @Gopal has the correct answer. As well as adding the following code, I had to set the reference to System.Web to copy local.

AppDomain.CurrentDomain.Load("System.Web");


来源:https://stackoverflow.com/questions/17105370/cannot-use-mvchtmlstring-ihtmlstring-with-razorengine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!