6

我有以下代码:

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.Templating.TemplateBase.RazorEngine.Templating.ITemplate.Run(ExecuteContext context) RazorEngine.Core\Templating\TemplateBase.cs:139

如果我删除布局线它工作正常

我的布局

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

想法?

4

2 回答 2

3

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

line 139:    return layout.Run(context);

如果“布局”变量为空,则可能出现 NullReferenceException。好的,什么是“布局”?

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

而且,我在这里看到,如果 _config.Resolver 为空,则 NullReference 是可能的。检查您的解析器。

于 2013-07-08T19:40:48.033 回答
0

我最终没有使用 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();
        }
    }
于 2013-07-10T00:15:35.497 回答