如果你想实现网站的安全性,那么你可以阅读 ASP.NET Web Pages 官网提供的教程,他们手里有一套写得很好的教程。
其次,你分享的那段代码
if(!WebSecurity.IsAuthenticated)
只会检查用户的 LoggedIn 属性,不会检查用户是否有帐户、角色等。它会检查用户登录时服务器设置的 cookie 或缓存
WebSecurity.Login(username, password);
这样,您只能检查用户是否已登录。 if用于显示
登录 |注册或用户名|退出
网站上的横幅。
如果您想添加一个新的安全层来检查用户的角色。使用这个
if (Roles.IsUserInRole("roleString")) {
// user is in the role
} else {
// user was in no role
}
您可以将此方法附加到您的IsAuthenticated 方法检查中以创建 2 层安全性。
检查这将是示例系统
if(WebSecurity.IsAuthenticated) {
// User is logged in!
if(Roles.IsUserInRole("someString")) {
// user is in role
// check other condition here...I was not able to understand
// the page condition...Sorry!
}
}
EDIT(检查新创建的用户)
当您在角色中添加用户时。 ASP.NET 实际上为该用户创建了一个新行,其中包含他所在的角色。
应该是这样的
UserId | RoleId
10 | 1
假设新创建的 userId 是 10,Admin 的 RoleId 是 1。您可以使用它来查询
var isInRoles = db.Query("SELECT * FROM webpages_UsersInRoles WHERE UserId =@0",
WebSecurity.CurrentUserId).Count();
if(isInRoles == 0) {
// No record found! So user must be a New User!
// Show X here...:)
}
这是在角色中检查用户的示例。或者检查用户是新用户还是以前的用户等等。