![](/img/trans.png)
[英]How to create context object accessible application-wide to store current user details in data access?
[英]Creating user profile that is accessible application-wide
我正在实现一个非常基本的登录系统,实际上并未使用任何现成的登录控件。 我的数据库包含以下表格:
UserProfiles:包含用户的详细信息
UserSecurityRoles:包含每个用户的安全角色
在我的asp.net应用程序中,我使用以下代码登录用户:
protected void Logon_Click(object sender, EventArgs e)
{
if (_BLSecurity.verifyUser(UserName.Text, UserPass.Text))
{
Response.Redirect("../Default.aspx");
}
else
{
Msg.Text = "Invalid credentials. Please try again.";
}
}
验证用户身份后,我需要将其包含在UserProfiles和UserSecurityRoles中的有关他的信息存储在我的Web应用程序中,以便我可以从自己拥有的每种表单中访问此数据,并根据其设置权限。
有什么想法我可以执行此操作吗?
您可以将UserProfilesData存储在会话中。 每个用户都有一个与他相关联的唯一会话。
protected void Logon_Click(object sender, EventArgs e)
{
if (_BLSecurity.VerifyUser(UserName.Text, UserPass.Text))
{
Session["currentUserProfile"] = GetUserProfile();
Response.Redirect("../Default.aspx");
}
else
{
Msg.Text = "Invalid credentials. Please try again.";
}
}
然后,每当需要UserProfile对象时,都可以使用currentUserProfile键从Session中获取它。
var userProfile = (UserProfile)Session["currentUserProfile"];
您可以为示例SessionContext
创建自定义类,其中将在登录时保存所有需要的数据。 之后,您可以创建每个UI.Page继承的类。 在此类中,您将拥有SessionContext
属性。
public SessionContext USession
{
get
{
if (base.Session["_USRSESS"] != null)
return (BO.SessionContext)base.Session[_USRSESS];
return null;
}
set
{
base.Session["_USRSESS"] = value;
}
}
当需要此用户数据时,将在每个页面中调用此属性。 在此处保存一个自定义类将使您可以将所需的所有内容放入会话中,而无需记住多个会话变量。
编辑:
如果您有BasicPage类
public class BasicPage : System.Web.UI.Page
{
public SessionContext USession
{
get
{
if (base.Session["_USRSESS"] != null)
return (BO.SessionContext)base.Session[_USRSESS];
return null;
}
set
{
base.Session["_USRSESS"] = value;
}
}
}
public partial class _Default : BasicPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
看到aspx.pages继承BasicPage
而BasicPage
继承UI.Page
。
当您重定向到“默认”页面时,您将需要以下内容:
SessionContext resSession = new SessionContext();
// I'm giving you example with standard bool property. You can put class property if you want.
resSession.IsAdmin = Convert.ToInt32(userRow["IsAdmin"]) == 1;
// this is Guid property for the User primary key, if you are using integer for primary key the property should be int.
resSession.UserID = (Guid)userRow["ID"];
BasicPage page = this.Page as BasicPage;
page.UserSession = session;
Response.Redirect("../Default.aspx");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.