具有布局的RazorEngine:对象引用未设置为对象的实例

本文关键字:设置 对象 实例 布局 RazorEngine 对象引用 | 更新日期: 2023-09-27 18:17:09

我有以下代码:

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: Object reference未设置为对象的实例。]RazorEngine.Templating.TemplateBase.RazorEngine.Templating.ITemplate。运行(ExecuteContext上下文)在c:'Users'Matthew'Documents'GitHub' razorenengine 'src'Core' razorenengine .Core' template 'TemplateBase.cs:139

如果我去掉布局线,效果会很好

My Layout

<!DOCTYPE html>
<html>
<head>
    @RenderSection("MetaSection", false)
    <title>@ViewBag.Title</title>
    @RenderSection("HeaderSection", false)
</head>
<body>
    @RenderBody()
</body>
</html>

想法吗?

具有布局的RazorEngine:对象引用未设置为对象的实例

我看了TemplateBase.cs的来源(https://github.com/Antaris/RazorEngine/blob/master/src/Core/RazorEngine.Core/Templating/TemplateBase.cs):

line 139:    return layout.Run(context);

NullReferenceException可能,如果'layout'变量为空。好的,什么是布局?

line 133: var layout = ResolveLayout(Layout);

更深入(https://github.com/Antaris/RazorEngine/blob/master/src/Core/RazorEngine.Core/Templating/TemplateService.cs):

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;
}

并且,我在这里看到,NullReference是可能的,如果_config。解析器为空。检查你的解析器

我最终没有使用Razor Engine

我的解决方案确实需要一个控制器上下文,所以我只使用一个来自被调用的控制器。在我的控制器

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