© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•11mo ago•
15 replies
Mark

HttpContextAccessor returns null for HttpContext in tests

I want to add some EF Core query filters inside my DbContext's OnModelCreating that ultimately leverage values from the user's ClaimsPrincipal, so I need to access the HttpContext for the request to grab it from that. Injecting IHttpContextAccessor into DbContext (long term I'd probably inject a TenantService instead) works when the app is run normally, but when running integration tests with WebApplicationFactory HttpContext always seems to be null.

Not sure if I'm missing something in my test setup or if my approach is wrong to begin with, but here's a contrived example: https://github.com/mwojtul/todos/blob/context-accessor/TodoApi/Data/AppDbContext.cs

If I run this app normally it'll work as expected and the /api/todos endpoint will always return an empty list, but my test suite that endpoint will return a todo
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

My HttpContext.User always return null
C#CC# / help
3y ago
Identity/EF collection returns null
C#CC# / help
2y ago
❔ .NET MAUI GetSystemService returns null
C#CC# / help
3y ago