ASP .NET Core using InMemory Cache per user

Jackal

I have a system where at some point, the user will be locked to a single page. In this situation his account his locked and he cannot be redirected to any other page and this is after authentication.

The verification is done using Page Filters accessing database. To improve performance I have used memory cache.

However, the result wasn't as expected because once the cache is used for a single user it will affect all the others.

As far as i know, you can separate caching using tag helpers per user but I have no idea if this is possible using code

public async Task<IActionResult> Iniciar(int paragemId, string paragem)
{
    var registoId = Convert.ToInt32(User.GetRegistoId());
    if (await _paragemService.IsParagemOnGoingAsync(registoId))
    {
        return new JsonResult(new { started = false, message = "Já existe uma paragem a decorrer..." });
    }
    else
    {
        await _paragemService.RegistarInicioParagemAsync(paragemId, paragem, registoId);
        _registoService.UpdateParagem(new ProducaoRegisto(registoId)
        {
            IsParado = true
        });

        await _registoService.SaveChangesAsync();
        _cache.Set(CustomCacheEntries.RecordIsParado, true, DateTimeOffset.Now.AddHours(8));

        return new JsonResult(new { started = true, message = "Paragem Iniciada." });
    }
}

here i only check first if the user account is blocked in the database first without checking cache first and then create the cache entry.

Every user will be locked because of this.

So my point is... Is there a way to achieve this like tag helpers?

Chris Pratt

The CacheTagHelper is different than cache in general. It works via the request and therefore can vary on things like headers or cookie values. Just using MemoryCache or IDistributedCache directly is low-level; you're just adding values for keys directly, so there's nothing here to "vary" on.

That said, you can compose your key using something like the authenticated user's id, which would then give each user a unique entry in the cache, i.e. something like:

var cacheKey = $"myawesomecachekey-{User.FindFirstValue(ClaimTypes.NameIdentifier)}";

Short of that, you should use session storage, which is automatically unique to the user, because it's per session.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

ASP .NET Core: How to cache data which depend on user input?

ASP.NET Core Testing - get NullReferenceException when initializing InMemory SQLite dbcontext in fixture

Net Core Identity one role per user

Custom Authentication using legacy user table in Asp.Net Core

how to get claims of another user using ASP.NET Core

Permissions per page in ASP.NET Core

Add Cache to ASP.NET Core response

Redis Cache in ASP.NET Core

How to cache resources in Asp.net core?

Asp.Net Core Cache Tag Helper

ASP.Net Core PWA Cache Query

asp.net proper async locking per cache key

PostSharp Caching MethodInterceptionAspect using ASP.NET Core in-memory cache

Using ASP.NET Core 3.1 custom distributed cache for respones caching

How to check if user is logged in to ASP.NET Core web application when using ASP.NET Core Web API to house identity

unable to update user via UserManager<TUser> using ef core 2.2 in asp.net core 2.2 app

User login using Email or Username gives null if user not found in ASP.NET Core MVC

Asp Core MVC 2.1 Authorization based on policies per user?

Implementing Cache manager using Dot Net core

Asp.net Core User Selectable CSS

Asp net Core Get user Windows username

ASP.NET Core Identity user groups

asp.net core not binding current User

Check if user is logged on in ASP.NET Core

Does .Net Core support User Secrets per environment?

ASP.NET Core DataProtection + Redis + Multiple Keys per Machine

Asp.Net Core async lazy initialization per request

How to Per-Request caching in ASP.net core

ASP.NET Core API JSON serializersettings per request