ASP.NET MVC4 Web API控制器应该在json结果属性中将Razor视图作为html返回。
我试过控制器
public class TestController : ApiController
{
public HttpResponseMessage Get()
{
var body = RenderViewToString<object>("~/Views/Broneeri/Schedule.cshtml", new object() );
return Request.CreateResponse(HttpStatusCode.OK, new { content = body } );
}
string RenderViewToString<T>(string viewName, T model)
{
ViewDataDictionary ViewData = new ViewDataDictionary(model);
TempDataDictionary TempData = new TempDataDictionary();
ControllerContext controllerContext = new System.Web.Mvc.ControllerContext();
controllerContext.RouteData = new RouteData();
controllerContext.RouteData.Values.Add("controller", "Schedule");
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
var viewContext = new ViewContext(controllerContext, viewResult.View, ViewData,
TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
}
但我有一个奇怪的例外
System.NotImplementedException was unhandled by user code
HResult=-2147467263
Message=The method or operation is not implemented.
Source=System.Web
StackTrace:
at System.Web.HttpContextBase.get_Items()
at System.Web.Mvc.VirtualPathProviderViewEngine.GetPath(ControllerContext controllerContext, String[] locations, String[] areaLocations, String locationsPropertyName, String name, String controllerName, String cacheKeyPrefix, Boolean useCache, String[]& searchedLocations)
at System.Web.Mvc.VirtualPathProviderViewEngine.FindPartialView(ControllerContext controllerContext, String partialViewName, Boolean useCache)
at System.Web.Mvc.ViewEngineCollection.Find(Func`2 lookup, Boolean trackSearchedPaths)
at System.Web.Mvc.ViewEngineCollection.Find(Func`2 cacheLocator, Func`2 locator)
...
在第
行var viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
如何从ASP.NET 4 Web API控制器中的视图返回HTML内容?
答案 0 :(得分:1)
您需要使用NuGet控制台Install-Package RazorEngine
。这是适用于我的代码:
using RazorEngine;
using RazorEngine.Templating;
string razorTemplate = "Hello @Model!";
string html = Engine.Razor.RunCompile(
razorTemplate,
"uniqueTemplateKey", // Guid.NewGuid().ToString() for example
modelType: typeof(string),
model: "Lorem Ipsum");
希望它有所帮助!