如何访问登录的用户从控制器之外吗? [英] How can I access the logged in user from outside of a controller?

查看:126
本文介绍了如何访问登录的用户从控制器之外吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用SignalR来处理我的申请MVC3从客户端的点击。

每次用户点击的东西的时候,我需要验证登录的用户。

如果这是一个MVC3控制器内,我会去:

 如果(User.Identity.IsAuthenticated)
{
    字符串的用户名= User.Identity.Name;    //我的code在这里。
}

不过,这code执行不是一个控制器类中。

基本上,我怎么可以访问登录的用户名从控制器外?


解决方案

  

基本上,我怎么可以访问登录的用户名从控制器外?


这取决于从那里,你想访问它们。如果您没有访问到的HttpContext 你总是可以尝试一个 HttpContext.Current.User 和祈祷它不会以空出于某种原因,例如像不同的线程或别的东西。这一点尤其更可能的SignalR取决于任务和大量的异步处理。如果是SignalR的轮毂内可以访问用户:

 公共类聊天:集线器
{
    公共无效美孚()
    {
        字符串的用户名= Context.User.Identity.Name;
    }
}

我个人不会你曾经使用 HttpContext.Current 建议。根据正是你要实现的目标,并在那里我向你保证,有更好的方式。

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.

这篇关于如何访问登录的用户从控制器之外吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆