Change layout for authenticated users in asp net core

When we talk about MVC on asp net, we know that the views are (in default approach) parts of our web page, because we have defined a layout that contains them. But sometimes we need/want to use a different layout, one of these scenario is for example when we have a different layout for logged/not logged users.

Let’s see an example, which use the simple AuthenticationCookie from NuGet package Microsoft.AspNetCore.Authentication.Cookies.

Our asp net core application when load views, like first approach it executes the “_ViewStart.cshtml” file which contains the layout definition.

This assignment tells to the application that the layout is contained in a file called “_Layout.cshtml” from the folder “Shared” in the same directory.

In this case is really simple to get what we want, we need just check if user is authenticated by our cookie or not.

What is happening here is really simple. We’re just telling to the application that, if the user is authenticated, must call the “_Layout.cshtml” file for the layout, else it should call the “_NotLoggedLayout.cshtml” file.

Note: both files must follow the asp net core rules, for example if you use  @RenderBody you should call in both file, not just in the first.