English 中文(简体)
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?

最佳回答

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.

问题回答

暂无回答




相关问题
Model-level authorization in Rails

I want to implement authorization in my Rails application on a model level (not controller), in a similar way that validation on models is done. What is the best way to do this? If it is implemented ...

What s the HTML code to limit the access to my web-page?

I have a question about HTML. I know that there is this mechanism that wouldn t allow users to get a direct access to a web-page unless they enter a password and a name. What s the HTML code for that?

Remotely authenticating client Windows user on demand

Suppose I am writing a server for a particular network protocol. If I know that the client is running on a Windows machine, is it possible for my server to authenticate the Windows user that owns the ...

How to keep RoleProvider from overriding custom roles?

I have an custom role provider that gets the roles a user belongs to from a database. I also have a custom authentication module registered in my web.config s httpModules which sniffs incoming HTTP ...

Mutual SSL - how much authentication is sufficient?

Suppose you have a mutual SSL service, which in addition to the SSL, has application authentication. Thus, clients provide certificates (as well as servers), but the client request (e.g., REST ...

热门标签