表单身份验证 - 使用对象数据源在FormView中显示当前登录的用户信息
-
06-07-2019 - |
题
在我的Web应用程序中,我使用带有cookie的Forms身份验证。在页面中,我希望在由ObjectDataSource支持的FormView中显示当前登录用户的信息。我的数据源有一个select方法,接受用户名作为参数,通过该用户名从数据库中请求用户数据。如何获取当前登录用户的用户名,并将其用作数据源的选择参数。
解决方案 2
相反,我选择使用数据源的Selecting事件并添加我需要的信息作为inputParameter。
其他提示
在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。
正如你所说的那样,“在我的网络应用程序中,我使用带有cookie的表单身份验证”。我假设你知道如何“记录”用户并将cookie发送到浏览器。如果您有任何问题,请告诉我。
不隶属于 StackOverflow