ControllerBase(asp.net mvc)中的HttpContext.Current.User为空

发布于 2024-09-19 17:48:06 字数 688 浏览 8 评论 0原文

我在 ASP.NET MVC 应用程序中有一个 ControllerBase 类。其他控制器继承自ControllerBase

我想访问 HttpContext.User.Identity.Name,但 HttpContextnull。怎么了?

public ControllerBase()
        {
            var dataManager=new DataManager();
            if (HttpContext.User.Identity.IsAuthenticated) // throws error
            {                    
                ViewData["assets"] = ud.BalanceFreeze + ud.Balance + ud.BalanceRealty;
                ViewData["onaccount"] = ud.Balance;
                ViewData["pending"] = ud.BalanceFreeze;
                ViewData["inrealty"] = ud.BalanceRealty;
            }

I have a ControllerBase class in an ASP.NET MVC Application. The other controllers inherit from ControllerBase.

I want to access HttpContext.User.Identity.Name, but HttpContext is null. What's the matter?

public ControllerBase()
        {
            var dataManager=new DataManager();
            if (HttpContext.User.Identity.IsAuthenticated) // throws error
            {                    
                ViewData["assets"] = ud.BalanceFreeze + ud.Balance + ud.BalanceRealty;
                ViewData["onaccount"] = ud.Balance;
                ViewData["pending"] = ud.BalanceFreeze;
                ViewData["inrealty"] = ud.BalanceRealty;
            }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白鸥掠海 2024-09-26 17:48:06

尝试将代码添加到 ControllerBase 中的此事件中:

protected override void Initialize(RequestContext requestContext){

}

Try adding your code to this event in your ControllerBase:

protected override void Initialize(RequestContext requestContext){

}
野生奥特曼 2024-09-26 17:48:06

您的控制器是在 ASP.NET 设置 HttpContext 之前构建的。就像 Nik 所说,您需要将此代码放入类中的重写方法中。

我还要指出,直接依赖 HttpContext 将无法在扩展此类的任何控制器上执行单元测试。这就是为什么 ControllerBase 类中的许多方法(如 Execute 方法)采用 RequestContext 作为参数。您可以说:

protected override void Execute(System.Web.Routing.RequestContext requestContext)
{
    var currentUser = requestContext.HttpContext.User;
    ...
}

...这使得可以使用“假”上下文创建和执行控制器以进行单元测试。

Your controller gets constructed before the HttpContext has been set by ASP.NET. Like Nik says, you need to put this code into an overridden method in your class.

I would also point out that depending on HttpContext directly will make it impossible to perform unit testing on any of your controllers that extend this class. This is why many of the methods (like the Execute method) in the ControllerBase class take a RequestContext as an argument. You can say:

protected override void Execute(System.Web.Routing.RequestContext requestContext)
{
    var currentUser = requestContext.HttpContext.User;
    ...
}

... which makes it possible to create and execute your controllers with "fake" contexts for unit testing purposes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文