我有以下代码:
public string View(string view, object model)
{
var template = File.ReadAllText(HttpContext.Current.Request.MapPath(@"~\Views\PublishTemplates\" + view + ".cshtml"));
if (model == null)
{
model = new object();
}
return RazorEngine.Razor.Parse(template, model);
}
我正在使用以下视图
@model NewsReleaseCreator.Models.NewsRelease
@{
Layout = "~/Views/Shared/_LayoutBlank.cshtml";
}
@Model.Headline
我得到了:
[NullReferenceException:对象引用未设置为对象的实例。] C:\ Users \ Matthew \ Documents \ GitHub \ RazorEngine \ src \ Core \ RazorEngine.Core \ Templating \ TemplateBase.cs:139
中的RazorEngine.Templating.TemplateBase.RazorEngine.Templating.ITemplate.Run(ExecuteContext context)
如果我删除布局线,它可以正常工作
我的布局
<!DOCTYPE html>
<html>
<head>
@RenderSection("MetaSection", false)
<title>@ViewBag.Title</title>
@RenderSection("HeaderSection", false)
</head>
<body>
@RenderBody()
</body>
</html>
思想?
答案 0 :(得分:3)
我查看了TemplateBase.cs(https://github.com/Antaris/RazorEngine/blob/master/src/Core/RazorEngine.Core/Templating/TemplateBase.cs)的来源:
line 139: return layout.Run(context);
NullReferenceException possibe,如果'layout'变量为null。好的,什么是'布局'?
line 133: var layout = ResolveLayout(Layout);
public ITemplate Resolve(string cacheName, object model)
{
CachedTemplateItem cachedItem;
ITemplate instance = null;
if (_cache.TryGetValue(cacheName, out cachedItem))
instance = CreateTemplate(null, cachedItem.TemplateType, model);
if (instance == null && _config.Resolver != null)
{
string template = _config.Resolver.Resolve(cacheName);
if (!string.IsNullOrWhiteSpace(template))
instance = GetTemplate(template, model, cacheName);
}
return instance;
}
而且,我在这里看到,如果_config.Resolver为null,则NullReference是可能的。检查你的解析器。
答案 1 :(得分:0)
我最终没有使用Razor Engine
我的解决方案确实需要一个控制器上下文,所以我只使用被调用的Controller中的一个。所以在我的控制器中
InstanceOfMyClass.ControllerCurrent = this
在MyClass中
public string RenderViewToString(string viewName, object model, string layoutName)
{
ControllerCurrent.ViewData.Model = model;
try
{
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerCurrent.ControllerContext, viewName, layoutName);
ViewContext viewContext = new ViewContext(ControllerCurrent.ControllerContext, viewResult.View, ControllerCurrent.ViewData, ControllerCurrent.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
catch (Exception ex)
{
return ex.ToString();
}
}