Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RazorEngine with layout : Object reference not set to an instance of an object

Tags:

c#

razor

I have the following code:

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

and I'm using the following view

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

I am getting:

[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

If I remove the Layout Line it works fine

My Layout

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

Thoughts?

like image 331
Jeff Avatar asked Jun 04 '13 21:06

Jeff


1 Answers

I looked sources of TemplateBase.cs (https://github.com/Antaris/RazorEngine/blob/master/src/Core/RazorEngine.Core/Templating/TemplateBase.cs):

line 139:    return layout.Run(context);

NullReferenceException possibe, if 'layout' variable is null. Ok, what is 'layout'?

line 133: var layout = ResolveLayout(Layout);

Go deeper (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;
}

And, i see here, that NullReference is possible, if _config.Resolver is null. Check your Resolver.

like image 200
oakio Avatar answered Oct 28 '22 13:10

oakio