I want to implement or use the AnonymousId\Anonymous user functionality found in the older ASP.NET MVC 4 system but in a ASP.NET Core 6 MVC application.

I have seen 3 NuGet packages which seem to do it but 2 are very old, and the third has very little documentation. In another very similar question, user KJensen (Using an anonymous user id in ASP.NET Core 3.1, like Request.AnonymousID from .NET 4.x?) mentioned using a NuGet package (NuGet AnonymousID but said he updated it for 3.1.

Unfortunately, he didn't elaborate, and I don't have the reputation points to make a comment or ask him (or not that I could figure out how to). I use stackoverflow every day, but I don't post much obviously.

I haven't tried much; I did include the NuGet package that KJensen mentioned but as he mentioned in his answer to his own question it did have a lot of dependencies. I guess I'd like to know how he updated it etc. I hope this is the correct mechanism to solve this issue.

1

There are 1 best solutions below

3
On BEST ANSWER

It does not need to be updated for version. You can find the corresponding Class Library in its GitHub repository and use it directly.

For example, I create a class library named AnonymousId and copy the file from GitHub to my class library:

enter image description here

Of course, you need to install the corresponding NuGet package to ensure that it will not report an error(Microsoft.AspNetCore.Http.Abstractions, Microsoft.AspNetCore.Http.Features and Microsoft.IdentityModel.Tokens): enter image description here

Then create your project under the same solution(ASP.NET Core 6 MVC): enter image description here

Reference class library:

<ItemGroup>
    <ProjectReference Include="..\AnonymousId\AnonymousId.csproj" />
</ItemGroup>

Add middleware in Program.cs:

app.UseAnonymousId();

In Controller:

public string Test()
{
    string anonymousId = "";
    IAnonymousIdFeature feature = HttpContext.Features.Get<IAnonymousIdFeature>();
    if (feature != null)
    {
        anonymousId = feature.AnonymousId;
    }
    return anonymousId;
}

Test Result:

enter image description here

Is this what you want?