I have a ControllerBase
class in an ASP.NET MVC Application. The other controllers inherit from ControllerBase
.
I want to access HttpContext.User.Identity.Name
, but HttpContext
is null
. What's the matter?
public ControllerBase()
{
var dataManager=new DataManager();
if (HttpContext.User.Identity.IsAuthenticated) // throws error
{
ViewData["assets"] = ud.BalanceFreeze + ud.Balance + ud.BalanceRealty;
ViewData["onaccount"] = ud.Balance;
ViewData["pending"] = ud.BalanceFreeze;
ViewData["inrealty"] = ud.BalanceRealty;
}
It just holds the username of the user that is currently logged in. After login successful authentication, the username is automatically stored by login authentication system to "HttpContext.Current.User.Identity.Name" property.
It won't work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which has no HTTP context associated with. Overall, don't use Application["Setting"] to store global stuffs, as they are not global as you discovered.
The HttpContext object constructed by the ASP.NET Core web server acts as a container for a single request. It stores the request and response information, such as the properties of request, request-related services, and any data to/from the request or errors, if there are any.
You can achieve this by manually settings HttpContext. User: var identity = new ClaimsIdentity("Custom"); HttpContext. User = new ClaimsPrincipal(identity);
Try adding your code to this event in your ControllerBase:
protected override void Initialize(RequestContext requestContext){
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With