Umbraco 13 - how to check if the current request is running in "preview" mode

In my code, I want to check if the current request is running in “preview” mode before I decide which view to use to render a component.

I have tried :

bool isPreviewMode = umbracoContext.InPreviewMode;

But it is returning true for both preview mode and non-preview mode.

Thanks
Kamal

This should work as is.

We have this in our code-base:

if (UmbracoContext?.InPreviewMode ?? false)
{
    // Some Code here
}

This is inside our BlockList component render(default.cshtml) so we can show errors for editors and not end users.

There are two things I can think of that could cause this.

  1. Your umbracoContext has a lowercase “U” at the beginning (Though this should give a compile error)
  2. The preview cookie or session data is not properly cleared.

Two is probably more likely and easy to test.
If you open a new private windows and test the page, without logging in to the backoffice, is the InPreviewMode still true?
If not then it’s some session data that is causing it, if it is still true, then I think we need a bit more context.
Is this inside a controller, service or af Razor page, is there any details in the HttpContext etc.

Hi Saeve,

Thanks so much for your reply .

I already injected IUmbracoContextAccessor into a class and passed IUmbracoContext as umbracoContext.

The issue is that once an editor save and preview a page from the back office, UmbracoContext?.InPreviewmode will always return true even if the editor decide to browse the site from the same browser through a normal url.

This is because UmbracoContext?.InPreviewmode - will always return the current user is in a preview mode and browsing the site.

This will create a confusion for the editor because both normal url and save & preview windows will be showing preview content.

For editors to see a published content they will have to use a different browser or log out of the previours browser.

Is there a way around this.

Regards.
Kamal

Dealing with editors is one of the many joys we have as Umbraco developers.

There’s, to my knowledge, not much you can do except for educating the editors.

As for your case, it sounds like the preview feature is working as intended.

To help the editors understand what to do, I would instruct them to end their preview session, when they’re done.

This should clear the session data that tells Umbraco it should show preview content.

Working around this in code is probably not a route you want to go down.

Agree with @Saeve unfortunately leaving preview mode is a training issue and it’s easy to miss even for seasoned editors.
I use the following syntax to check btw thank to @rickbutterfield from his Block Preview docs:

if (umbracoContext.UmbracoContext.InPreviewMode) {
// some code
}

Thanks so much to you both.

1 Like