[英]Why does System.Web.HttpContext.Current.User resolve during a controller constructor, but User.Identity does not
Rowan Freeman's answer to this question describes why User.Identity
is null during the constructor of a controller. 罗恩·弗里曼(Rowan Freeman)对这个问题的回答描述了为什么在控制器的构造函数期间User.Identity
为null。 A comment on the same question points out that System.Web.HttpContext.Current.User
does result in the expected value in the same context. 对同一问题的评论指出, System.Web.HttpContext.Current.User
确实会在同一上下文中产生期望值。
Why is System.Web.HttpContext.Current.User
valid during the controller's constructor even though User.Identity
is not? 为什么System.Web.HttpContext.Current.User
在控制器的构造函数期间有效,即使User.Identity
无效?
Will using System.Web.HttpContext.Current
during the constructor of a controller potentially result in bugs? 在控制器的构造函数中使用System.Web.HttpContext.Current
会导致错误吗?
Edit for clarification: 编辑以澄清:
From the linked article, regarding User.Identity
: "Controller instantiation will occur before authorization takes place. Even if your MVC application calls RenderAction() several times and you end up creating say, five different controllers, those five controllers will be created before any OnAuthorization takes place." 在链接的文章中,关于User.Identity
:“控制器实例化将在授权发生之前发生。即使您的MVC应用程序多次调用RenderAction()并最终创建例如五个不同的控制器,也将在创建任何五个控制器之前创建这五个控制器。发生了OnAuthorization。”
Does the above paragraph not apply to System.Web.HttpContext.Current
? 上面的段落不适用于System.Web.HttpContext.Current
吗? I am hoping to better understand the nuance between the two that makes them appear to behave differently, to hopefully understand whether System.Web.HttpContext.Current
is acceptable to use outside of an individual action but inside the controller. 我希望能更好地理解两者之间的细微差别,使它们表现出不同的行为,以期希望了解System.Web.HttpContext.Current
是否可以在单个动作之外但在控制器内部使用。
Will using System.Web.HttpContext.Current during the constructor of a controller potentially result in bugs? 在控制器的构造函数中使用System.Web.HttpContext.Current会导致错误吗?
It will introduce an undesirable dependency, which will, for example, prevent you from being able to unit test the controller properly. 它将引入不良的依赖关系,例如,这将阻止您无法对控制器进行正确的单元测试。
You might consider overriding Controller.Initialize
instead to add your own initializ 您可以考虑重写Controller.Initialize
来添加自己的Initializ
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.