Call UseSession after UseRouting and before UseEndpoints

solrevdev

John Smith

Posted on March 5, 2020

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 🎉

💖 💪 🙅 🚩
solrevdev
John Smith

Posted on March 5, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related