Chaitwo
Chaitwo

Reputation: 269

HttpContext.Session.Abandon() doesn't work in MVC core. Session.clear doesn't log my user out

I get an error that says "ISession does not contain a definition for 'Abandon' and no accessible extension method 'Abandon' accepting a first argument of type 'ISession' could be found".

I have tried using session.clear but even after logging out if I open the website the user is logged in.

This is the error I get

enter image description here

Upvotes: 2

Views: 8632

Answers (3)

BrettB
BrettB

Reputation: 114

HttpContext.Session.Clear() wasn't working for me on my live site in the Controller for my Account/Logout page.

I found out that setting a href of /Account/Logout/ was the problem. I changed my links to /Account/Logout.

If you're having Session problems in .NET Core 3.1 then try this. It may also account for why I couldn't get Cookie Authentication to work - I gave up in the end and switched to using Sessions.

Upvotes: 0

Chaitwo
Chaitwo

Reputation: 269

It seems my session is being stored in cookies and not getting cleared/deleted when used session.clear()

so I've used this and it seems to work like a charm.

foreach (var cookie in Request.Cookies.Keys)

        {
            if (cookie == ".AspNetCore.Session")
                Response.Cookies.Delete(cookie);
        }

Upvotes: 1

Rahul Sharma
Rahul Sharma

Reputation: 8311

This is how I have implemented Session in my ASP .NET CORE project:

Create a SessionTimeout filter:

public class SessionTimeout : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (context.HttpContext.Session == null ||!context.HttpContext.Session.TryGetValue("UserID", out byte[] val))
        {
            context.Result =
                new RedirectToRouteResult(new RouteValueDictionary(new
                {
                    controller = "Pages",
                    action = "SessionTimeout"
                }));
        }
        base.OnActionExecuting(context);
    }
}

Register this filter in your Startup.cs:

In your ConfigureServices method:

services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(10);               
            });

In your Configure add:

app.UseSession();

And finally decorate your class/method with your filter like:

    [SessionTimeout]
    public class DashboardController : Controller

To destroy your session based on Logout event from your View:

public IActionResult Logout()
        {
            HttpContext.Session.Clear();
            return RedirectToAction("Login", new { controller = "Pages" });
        }

Upvotes: 3

Related Questions