.NET Application_BeginRequest - 如何获取用户引用?
我试图在 Global.asax 文件的 Application_BeginRequest
中获取对用户对象的引用。我正在使用属性 Context.User
,但收到 NullReferenceException
。 是否可以在Application_BeginRequest中获取用户对象引用?
I'm trying to get a reference to the user object in my Global.asax file's Application_BeginRequest
. I'm using the property Context.User
but I get a NullReferenceException
. Is it possible to get a user object reference in Application_BeginRequest?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无权访问 User 对象,因为请求尚未经过身份验证。
尝试使用 Application_AuthenticateRequest 代替。
以下是所有 Global.asax 事件的解释:
https://web .archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5771721.html
以及应用程序生命周期的 MSDN 演练:
http://msdn.microsoft.com/en-us/library/ms178473.aspx编辑
:
我明白你在做什么。将 if 语句更改为 if not 语句(抱歉,如果语法错误,我不使用 VB.NET):
您会注意到此方法多次被命中。直到第二次或第三次才会抛出异常。这是因为每个请求都遵循应用程序生命周期。因此,不应在用户为空时执行任何操作,而应该在用户不为空时执行该操作。
如果您的目标是动态限制访问,则应创建一个单独的 HttpModule 并将其分配给您要限制的文件
但是,您需要小心,不要重写整个 ASP.NET应用程序安全基础设施。相反,您可以根据角色限制对某些文件夹的访问。
You don't have access to the User object because the request hasn't yet been authenticated.
Try using Application_AuthenticateRequest instead.
Here is an explanation of all Global.asax events:
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5771721.html
And the MSDN walkthrough of the application lifecycle:
http://msdn.microsoft.com/en-us/library/ms178473.aspx
Edit:
I see what you're doing. Change your if statement to and if not statement (sorry if syntax is wrong, I don't use VB.NET):
You'll notice that this method gets hit more than once. The exception won't be thrown until the second or third time. That is because every request follows the application lifecycle. So, instead of performing whatever action when the user is null, you should perform it when the user is not null.
If your goal is to restrict access dynamically, you should create a separate HttpModule and assign it to the files you're restricting
However, you'll need to be careful not to undertake rewriting the entire ASP.NET Application Security infrastructure. You can, instead, restrict access to certain folders based on role.
不可以,您必须使用
Application_AuthenticateRequest
来代替。这是您拥有用户的最早点。No, you must use
Application_AuthenticateRequest
instead. That's the earliest point where you have an user.