.NET Application_BeginRequest - 如何获取用户引用?

发布于 2024-09-06 16:36:12 字数 209 浏览 6 评论 0原文

我试图在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心凉 2024-09-13 16:36:13

您无权访问 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):

 Sub Application_AuthenticateRequest() 
   If Context.User <> Nothing Then 
      Throw New Exception("User now exists") 
 End Sub 

您会注意到此方法多次被命中。直到第二次或第三次才会抛出异常。这是因为每个请求都遵循应用程序生命周期。因此,不应在用户为空时执行任何操作,而应该在用户不为空时执行该操作。

如果您的目标是动态限制访问,则应创建一个单独的 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):

 Sub Application_AuthenticateRequest() 
   If Context.User <> Nothing Then 
      Throw New Exception("User now exists") 
 End Sub 

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.

予囚 2024-09-13 16:36:13

不可以,您必须使用 Application_AuthenticateRequest 来代替。这是您拥有用户的最早点。

No, you must use Application_AuthenticateRequest instead. That's the earliest point where you have an user.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文