user13431554
user13431554

Reputation:

C#: Add Custom Properties In HttpContextAccessor

Is there a way to add Custom properties in HttpContextAccessor in C# Net Core?

Say, create new property called: Favoritefood Property, or CreatedByUser (coming from special function) and assign a value? this is simple example below,

We want to eventually bring custom properties into the DbContext layer, not only audit related, etc.

public class AuditableDbContext: DbContext
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public AuditableDbContext(DbContextOptions<AuditableDbContext> options, IHttpContextAccessor httpContextAccessor)
        : base(options)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    private void ApplyCreatedBy()
    {
        var modifiedEntities = ChangeTracker.Entries<IFood>().Where(e => e.State == EntityState.Added);
        foreach (var entity in modifiedEntities)
        {
            entity.Property("Food").CurrentValue = GetFoodMethod();
        }
    }

    public override int SaveChanges()
    {
        ApplyCreatedBy();
        return base.SaveChanges();
    }

Resources:

Log UserName and IP with Custom Properties in Application Insight .Net Core 2.1

Add Custom properties to ClaimsPrincipal user in asp.net core 2

Upvotes: 3

Views: 3100

Answers (1)

MichaC
MichaC

Reputation: 13381

Not 100% sure what your example has to do with adding custom things into the http context. But yes, HttpContext has an items collection which you can use to store context specific state information.

_httpContextAccessor.HttpContext.Items["key"] = "some random value";

You can get the context via the ContextAccessor.

Upvotes: 6

Related Questions