私の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 に答える