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

后端 未结 1 1836
借酒劲吻你
借酒劲吻你 2021-01-04 12:03

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

1条回答
  •  长发绾君心
    2021-01-04 12:13

    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.

    0 讨论(0)
提交回复
热议问题