如何从抽象基本控制器访问 HttpContext?
我创建了一个抽象控制器类 (ApplicationController
) 来处理一些用户身份验证,但在调用代码时 HttpContext
未初始化。
public abstract class ApplicationController : Controller
{
public ApplicationController()
{
string myuser = HttpContext.User.Identity.Name; // NullReferenceException
}
}
I have created an abstract controller class (ApplicationController
) for handling some user authentication, but HttpContext
is not initialized when the code get called.
public abstract class ApplicationController : Controller
{
public ApplicationController()
{
string myuser = HttpContext.User.Identity.Name; // NullReferenceException
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Yassir 关于在抽象类中使用受保护的构造函数是正确的。但你是对的,它不能解决你的问题——HttpContext 仍然没有完全填充,所以你会得到空引用异常。
不管怎样,解决方案很简单——重写控制器的Initialize方法:
Yassir is correct about using protected constructors in abstract classes. But you are correct that it doesn't solve your problem--the HttpContext still ain't quite populated yet so you get null reference exceptions.
Anyhow, the solution is simple--override the Initialize method of the controller:
尝试使您的 .ctor 受到保护
,并确保您没有错过此 using 指令:
try to make your .ctor protected
also make sure you are not missing this using directive: