I'm using SignalR to process clicks from the client on my MVC3 application.
Every time a user clicks something, I need to verify the logged in user.
If this were inside an MVC3 controller, I would go:
if (User.Identity.IsAuthenticated)
{
string username = User.Identity.Name;
//My code here.
}
However, this code execution is not inside a Controller class.
Basically, how can I access the logged in users name from outside a controller?
Basically, how can I access the logged in users name from outside a controller?
It depends from where you want to access them. If you don't have access to an HttpContext
you could always try an HttpContext.Current.User
and pray that it won't be null for some reason like for example different thread or something else. This is especially more possible with SignalR which depends on Tasks and lots of asynchronous processing. If it is inside a SignalR's hub you have access to the user:
public class Chat: Hub
{
public void Foo()
{
string username = Context.User.Identity.Name;
}
}
Personally I wouldn't recommend you ever using HttpContext.Current
. Depending on what exactly you are trying to achieve and where I guarantee you that there are better ways.
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