在我的 Web 应用程序中,我使用带有 cookie 的表单身份验证。在一个页面中,我希望在由 ObjectDataSource 提供支持的 FormView 中显示当前登录用户的信息。我的数据源有一个 select 方法,它接受用户名作为参数,通过该用户名从数据库中请求用户数据。如何获取当前登录用户的用户名并将其用作数据源的选择参数。
1915 次
2 回答
1
在 Global.asax.. 你应该写:
protected void Application_AuthenticateRequest(object sender, EventArgs e) {
if (Request.PhysicalPath.EndsWith(".aspx") || Request.PhysicalPath.EndsWith(".axd"))
SecurityManager.SetPrincipal();
}
SecurityManager.SetPrincipal() 方法应如下所示:
// variable we'll use to set HttpContext.Current.User
IPrincipal principal = null;
FormsIdentity identity;
//IsAuthenticated will be automatically set by .NET framework
if (HttpContext.Current.Request.IsAuthenticated)
{
// (FormsIdentity)HttpContext.Current.User.Identity will
// be filled automatically by the .NET framework when using forms authentication
identity = (FormsIdentity)HttpContext.Current.User.Identity;
// This User class must be defined BY YOU
User userProfile;
// this user data is the data that you entered when you created the ticket.
// this should be a security token that would allow you to GET THE USER FROM IT
String userData = (((FormsIdentity)identity).Ticket).UserData;
try
{
// UserHelper is a class that must be able to OBTAIN a USER given a SECURITY TOKEN.
// remember, you created this token when you created the ticket you used in the cookie.
userProfile = UserHelper.GetUser(userData);
// AuthenticatedPrincipal must implement IPrincipal. Consider deriving from GenericPrincipal.
// Your IPrincipal implementations must hold a reference to the UserClass you created
principal = new AuthenticatedPrincipal(identity, userProfile);
}
catch
{
FormsAuthentication.SignOut();
// This is analogous to AuthenticatedPrincipal
principal = new AnonymousPrincipal(new GuestIdentity(), UserHelper.GetUser(null));
}
}
else
{
principal = new AnonymousPrincipal(new GuestIdentity(), UserHelper.GetUser(null));
}
// Now we make our principal, that holds a reference to the currently
// logged user, globally visible
HttpContext.Current.User = principal;
据我所知,ObjectDataSource 允许您编写一个数据访问层类并将该类的一些方法映射到 DataSource 操作。您可以从这些方法中访问 HttpContext.Current.User。
正如您所说,您是“在我的 Web 应用程序中,我使用带有 cookie 的表单身份验证”。我假设您知道如何“记录”用户并将 cookie 发送到浏览器。如果您对此有任何问题,请告诉我。
于 2009-10-25T04:08:05.127 回答
0
相反,我选择使用数据源的 Selecting 事件并将我需要的信息添加为 inputParameter。
于 2009-10-29T18:28:25.987 回答