Skip to content

Guard the Site Settings lookup in _Layout.cshtml #330

Description

@deanleigh

Umbootstrap.Web/Views/_Layout.cshtml:5 assumes Site Settings is always present:

var siteSettings = Model.Root().FirstChild<SiteSettings>();

FirstChild<T>() returns SiteSettings?, but the value is passed straight into two partials that declare it as non-nullable:

  • Views/FeaturesGlobal/header.cshtml@inherits UmbracoViewPage<SiteSettings>
  • Views/FeaturesGlobal/footer.cshtml@inherits UmbracoViewPage<ContentModels.SiteSettings>

No warning fires today because @inherits/@model declarations are nullable-oblivious, even with <Nullable>enable</Nullable> set in the csproj. But the null is real: if the Site Settings node is missing, unpublished, or not the first child of the root, the site dies with a bare NullReferenceException somewhere inside a partial, with nothing pointing at the actual cause.

Suggested fix

Fail at the point of retrieval with a message that names the problem:

var siteSettings = Model.Root().FirstChild<SiteSettings>()
    ?? throw new InvalidOperationException(
        "The Site Settings node is missing or unpublished. It must exist as the first child of the site root.");

This also narrows the type to non-null for every downstream use, so it stays clean if anyone later introduces a strongly-typed view model taking SiteSettings.

Why this is worth doing now

In a site built from this template, adding a view model that takes a non-nullable SiteSettings immediately surfaces this as a CS8604 warning. That is exactly what happened in a downstream project (a MetaViewModel for the Head/_meta partial), and the fix belonged in _Layout rather than in the new view model.

Hardening it in the template means sites generated from it start correct, and get a useful error message instead of an NRE when an editor unpublishes the wrong node.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions