Call UseSession after UseRouting and before UseEndpoints

Today, I fixed a bug where session cookies were not being persisted in an ASP.Net Core Razor Pages application.

The answer was in the documentation.

To quote that page:

The order of middleware is important. Call UseSession after UseRouting and before UseEndpoints

So my code which did work in the past, but probably before endpoint routing was introduced was this:

app.UseSession();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapRazorPages();
});

And the fix was to move UseSession below UseRouting

app.UseRouting();
app.UseSession();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapRazorPages();
});

Success 🎉