开发者

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 contro开发者_运维百科ller?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜