ControllerBase(asp.net mvc)中的HttpContext.Current.User为空
我在 ASP.NET MVC 应用程序中有一个 ControllerBase
类。其他控制器继承自ControllerBase
。
我想访问 HttpContext.User.Identity.Name
,但 HttpContext
为 null
。怎么了?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将代码添加到 ControllerBase 中的此事件中:
Try adding your code to this event in your ControllerBase:
您的控制器是在 ASP.NET 设置 HttpContext 之前构建的。就像 Nik 所说,您需要将此代码放入类中的重写方法中。
我还要指出,直接依赖 HttpContext 将无法在扩展此类的任何控制器上执行单元测试。这就是为什么
ControllerBase
类中的许多方法(如 Execute 方法)采用RequestContext
作为参数。您可以说:...这使得可以使用“假”上下文创建和执行控制器以进行单元测试。
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 aRequestContext
as an argument. You can say:... which makes it possible to create and execute your controllers with "fake" contexts for unit testing purposes.