How-to: clear all cookies in asp.net core 2.1

 

Sometimes your users need a fresh start. Clearing all cookies from a response in asp.net core can be easy and straight forward, if you know where to look. Here's a clean way to do it.

door Corstiaan Hesselink

Laatste wijziging: Monday May 21, 2018Leestijd: 4 minutes

Have you ever contacted support of one of the web app’s you use often? Chances are that their proposed solution to help you contained some variation of “clear your cookies and try again”. Because cookies are often used to track a user’s session or state (like if they signed in or not) cookies heavily influence the user’s experience with your web app. This is one of the reasons remote support sometimes asks you to clear your cookies. It gives the user fresh start. It’s as if he is using your app again for the first time.

As a developer actually building web app’s it’s good to know how to give your users such a fresh start. You might want to clear all cookies when a user signs out for example, depending on your situation.

Asp.net core can be daunting when you are new to the framework and we all know the feeling of digging around the docs or sifting through all the options auto complete has to offer. It’s not fun. At all.

To save you some time, here’s a short how-to for clearing all cookies in asp.net core 2.1. I assume you already know how to set a cookie, otherwise you would not need to know how to delete them :-).

Let’s say you want to clear all cookies for the current user when he visits the home page. You would start with a controller like this:

1
2
3
4
5
6
7
8
9
10
namespace clearcookiesdemo.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

This controller does nothing special yet. It justs returns the corresponding view.

To delete all cookies for the current user (or rather the current session) when he hits the index we need to iterate over all cookies in the current session.

The Request object is available by default in the controller and it exposes a IRequestCookieCollection property named, you guessed it, Cookies. This is the collection we need to iterate over if you want to delete all cookies in one go.

To get this to work we modify the IActionResult Index() like so:

1
2
3
4
5
6
7
8
public IActionResult Index()
{
    foreach (var cookieKey in Request.Cookies.Keys)
    {
        Response.Cookies.Delete(cookieKey);
    }
    return View();
}

Notice how we loop over the Keys property of the cookie collection and not just the Cookies collection itself. This property gives us all the available cookie keys in one clean sweep. Then, inside the foreach we delete the cookies from the Response using it’s key.

And that’s all there is to it.

Kom bij de club

Meld je aan en ontdek als eerste nieuws, kennis en inzicht over software, development en technologie. Direct in je mailbox, met mijn geen-spam-garantie™.