在控制器的构造函数中访问 HttpContext.Request [英] accessing HttpContext.Request in a controller's constructor

查看:20
本文介绍了在控制器的构造函数中访问 HttpContext.Request的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注这个 ASP.NET来自 Microsoft 的 MVC 教程:

我的代码略有不同,我试图在控制器的构造函数中访问 HttpContext.Request.IsAuthenticated.

My code is slightly different, where I'm trying to access HttpContext.Request.IsAuthenticated in the controller's constructor.

namespace SCE.Controllers.Application
{
    public abstract class ApplicationController : Controller
    {
        public ApplicationController()
        {
            bool usuario = HttpContext.Request.IsAuthenticated;
        }           
    }
}

问题在于 HttpContext 始终为 null.

The problem is that HttpContext is always null.

有没有办法解决这个问题?

Is there a solution to this?

推荐答案

Controller 在调用 Index action 之前被实例化了很多,在构造的那一刻 HttpContext 确实不可用.在控制器方法 Index 中引用它有什么问题?

The Controller is instantiated significantly prior to the point where the Index action is invoked, and at the moment of construction HttpContext is indeed unavailable. What's wrong with referencing it in your controller method Index?

这篇关于在控制器的构造函数中访问 HttpContext.Request的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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