.NET的Application_BeginRequest - 如何获得用户参考? [英] .NET Application_BeginRequest - How to get User reference?

查看:967
本文介绍了.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?

推荐答案

您没有访问用户对象,因为请求尚未得到验证。

You don't have access to the User object because the request hasn't yet been authenticated.

尝试使用Application_AuthenticateRequest代替。

Try using Application_AuthenticateRequest instead.

下面是所有的Global.asax事件的解释:
<一href=\"https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5771721.html\" rel=\"nofollow\">https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5771721.html

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

和应用程序生命周期的MSDN演练:
http://msdn.microsoft.com/en-us/library/ms178473.aspx

And the MSDN walkthrough of the application lifecycle: http://msdn.microsoft.com/en-us/library/ms178473.aspx

编辑:
我看到你在做什么。改变你的if语句,如果不声明(抱歉,如果语法错了,我不使用VB.NET):

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.

如果你的目标是动态地限制访问,你应该创建一个单独的HttpModule并将其分配给你限制文件

不过,你需要小心,不要进行重写整个ASP.NET应用程序安全性的基础设施。你可以,而是限制访问基于角色的某些文件夹。

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.

这篇关于.NET的Application_BeginRequest - 如何获得用户参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆