11

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?

Only Bolivian Here
  • 35,719
  • 63
  • 161
  • 257

1 Answers1

14

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I've tried it out using HttpContext.Current and it works. What are some of pitfalls you describe? How would it the context be null? Why do you recommend I never use this? – Only Bolivian Here Sep 02 '11 at 22:29
  • @Sergio Tapia, the context will be null if the code you are executing is for example on some background thread. You didn't answer my question: where are you trying to access this information? – Darin Dimitrov Sep 02 '11 at 22:30
  • Ah I see what you're saying, Context is part of the Hub class. Is this what you mean? I should use `Context` instead of `HttpContext`? – Only Bolivian Here Sep 02 '11 at 22:30
  • @Sergio Tapia, if you are inside a Hub you could use `Context.User.Identity.Name` to get the currently connected username. – Darin Dimitrov Sep 02 '11 at 22:31
  • 1
    That's fantastic, some very smart people worked on this library. Thanks for your time. – Only Bolivian Here Sep 02 '11 at 22:33
  • Yes, please don't use HttpContext.Current :) – davidfowl Sep 03 '11 at 04:07
  • What's a better way of doing Context.User.Identity.Name in an action filter? I must admit, I've never had an issue with using this to store the id of a logged in user. – Ian Warburton Nov 20 '11 at 12:23