Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the logged in user from outside of a controller?

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?

like image 895
Only Bolivian Here Avatar asked Sep 02 '11 22:09

Only Bolivian Here


Video Answer


1 Answers

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.

like image 124
Darin Dimitrov Avatar answered Oct 25 '22 13:10

Darin Dimitrov