dotnet / dotnet/aspnetcore

CookieTempDataProvider should not call DeleteCookie just because TempData currently has no values

Open
#46,189 2 comments 1 reaction 0 assignees View on GitHub
area-mvc bug
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

On every request our app is checking TempData (using the default cookie storage) for several values.

On almost all requests, these values are not set - and yet, on every single response this header is attached:

`Set-Cookie: .AspNetCore.Mvc.CookieTempDataProvider=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; samesite=lax; httponly`

From what I can tell, that's because in `CookieTempDataProvider.SaveTempData`, if there are no TempData values, it calls `_chunkingCookieManager.DeleteCookie(context, _options.Cookie.Name, cookieOptions);`

This should be unnecessary - and it's particularly problematic with Output Caching since that only applies to requests that don't set cookies, so checking TempData effeectively disables output caching.

### Expected Behavior

Reading TempData without modifying it should not set a cookie.

Perhaps this code block in CookieTempDataProvider can be removed?

```
else
{
_chunkingCookieManager.DeleteCookie(context, _options.Cookie.Name, cookieOptions);
}
```

Edit: May make sense to actually modify it like so:

```
else if (context.Request.Cookies.ContainsKey(_options.Cookie.Name))
{
_chunkingCookieManager.DeleteCookie(context, _options.Cookie.Name, cookieOptions);
}
```

I've copied the code from CookieTempDataProvider into my project and modified it as shown above which has fixed the issue.

It also might make sense to modify chunkingCookieManager to do that check directly - as in to only set the already-expired cookie in the case that the cookie actually existed on the request in the first place

### Steps To Reproduce

Just check TempData without modifying it. The "delete" cookie gets appended with every request.

https://github.com/DanielStout5/TempDataDeleteCookieExample

### Exceptions (if any)

_No response_

### .NET Version

7.0.101

### Anything else?

ASP.NET Core 7.0.2
Visual Studio 2022

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.