gpt4 book ai didi

c# - 布局为 : Object reference not set to an instance of an object 的 RazorEngine

转载 作者:太空狗 更新时间:2023-10-29 21:50:43 25 4
gpt4 key购买 nike

我有以下代码:

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

我正在使用以下 View

@model NewsReleaseCreator.Models.NewsRelease
@{
Layout = "~/Views/Shared/_LayoutBlank.cshtml";
}
@Model.Headline

我得到:

[NullReferenceException: Object reference not set to an instance of an object.] RazorEngine.Templating.TemplateBase.RazorEngine.Templating.ITemplate.Run(ExecuteContext context) in c:\Users\Matthew\Documents\GitHub\RazorEngine\src\Core\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>

想法?

最佳答案

我查看了 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 是可能的。检查您的解析器。

关于c# - 布局为 : Object reference not set to an instance of an object 的 RazorEngine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16928067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com