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

瘦欲@ 提交于 2019-11-30 02:58:46

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/7289724/how-can-i-access-the-logged-in-user-from-outside-of-a-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!