即使您不想使用成员资格和角色提供者数据存储,您仍然可以使用身份验证。相信我,这比构建自己的要容易得多。以下是它的工作原理:
我们会说您已经设置了用于检索用户名和密码的用户存储空间。为了简单起见,我将假设您有一个名为 DataLayer 的静态类,其中包含用于从数据库(或您使用的任何存储)中提取信息的数据检索方法。
首先,您需要一种让用户登录的方法。因此,请设置一个包含用户名和密码字段的页面。然后在页面发布的action方法中设置一个快速if语句:
if (DataLayer.UserExists(userModel.Username))
{
User userFromDB = DataLayer.GetUser(userModel.Username);
if (userFromDB.Password == userModel.Password)
{
FormsAuthentication.SetAuthCookie(userFromDB.Username, checkBoxRememberMe.Checked);
//Use userFromDB as the username to authenticate because it will
//preserve capitalization of their username the way they entered it
//into the database; that way, if they registered as "Bob" but they
//type in "bob" in the login field, they will still be authenticated
//as "Bob" so their comments on your blogs will show their name
//the way they intended it to.
return "Successfully logged in!";
}
}
return "Invalid username or password.";
现在他们已通过身份验证,您可以在代码中使用 Page.User.Identity.IsAuthenticated 来确定他们是否已登录。像这样:
if (User.Identity.IsAuthenticated)
{
DataLayer.PostBlogComment(User.Identity.Name, commentBody);
//Then in your controller that renders blog comments you would obviously
//have some logic to get the user from storage by the username, then pull
//their avatar and any other useful information to display along side the
//blog comment. This is just an example.
}
此外,您可以将整个操作方法甚至整个控制器锁定给通过表单身份验证提供程序进行身份验证的用户。您所要做的就是将这些标签添加到您的操作方法/控制器中:
[Authorize]
public ActionResult SomeActionMethod()
{
return View();
}
[Authorize] 属性将阻止未登录的用户访问该操作方法,并将他们重定向到您的登录页面。如果您使用的是内置角色提供程序,则可以使用相同的属性过滤掉角色。
[Authorize(Roles="Admin, SalesReps")]
public ActionResult SomeActionMethod()
{
return View();
}
这些属性也可以添加到控制器类之上,以将其逻辑应用于整个控制器。
编辑:要注销用户,您只需拨打FormsAuthentication.SignOut();