在ActionResult方法之外查找用户 [英] Find User Outside of ActionResult Methods

查看:47
本文介绍了在ActionResult方法之外查找用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问了这个问题即使该答案解决了我收到的错误消息..我也想找到当前正在使用该应用程序的用户一次..而不必在每个操作方法中编写此信息...

Even though that answer resolves the error message I was receiving.. I would like to find the user that is currently using the application one time.. instead of having to write this inside of every action method...

var userIdentity = HttpContext.User.Identity.Name.Split('\\')[1].Replace(".", " ");

我想在任何ActionResult方法之前将其放在控制器类的顶部,这样我可以只在每个action方法中引用变量,而不是如上所述的整行..甚至可以在构造函数中设置它这样,我根本就不必引用它.

I would like to have this at the top of the controller class before any ActionResult methods, that way I can just reference the variable in each action method instead of the entire line as seen above.. or even set this in a constructor that way I don't have to reference it at all.

感谢您的帮助.

推荐答案

您可以创建扩展方法

public static class ExtensionHelper {
    public static string UserIdentity(this HttpContext context)
    {
        return context.User.Identity.Name.Split('\\')[1].Replace(".", " ");
    }
}

在控制器中的用法

var identity = HttpContext.UserIdentity()

如果看起来更干净,您可以对控制器扩展执行相同的操作.

You could do the same thing with a controller Extension if that seems cleaner.

public static class ExtensionHelper
{
    public static string UserIdentity(this Controller controller)
    {
        return controller.HttpContext.User.Identity.Name.Split('\\')[1].Replace(".", " ");
    }
}

在控制器中的用法

var identity = this.UserIdentity()


那就是说,如果您使用适当的IoC或DI框架,然后具有Context类,那么在存在用户上下文的情况下,您可以注入该类来启动此状态,这样会更干净.然后,您可以将其注入到Controller中,而不必尝试扩展您的Controller.我个人最喜欢的是AutoFac,但是有很多,使用几乎所有的DI框架来完成此操作都相对简单.


That said it would be cleaner if you used a proper IoC or DI framework and then had a Context class that you could inject that initiated this state if there was a user context. You could then inject this into your Controller instead of trying to extend your controller. My personal favorite is AutoFac but there are many out there and accomplishing this using almost any DI framework is relatively simple.

这篇关于在ActionResult方法之外查找用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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