Many Web applications require access to certain resources (such as specific pages) to ensure that only authenticated users can access these resources. The default Web application project template of ASP. net mvc provides a controller and some data models and views. You can use these components to add ASP. NET form authentication for applications.
1. Account controller, model, and view
In the Controllers folder, The AccountController class contains some operation methods that can register a new user, log on to and log off a user in an application, and change the password of an existing user. In the Views folder, the Accounts folder contains Views that support these operations. In the Models folder, The AccountModels class contains classes that define data objects, services, and verification routines that support form authentication.
In the Views folder, the Shared sub-folder contains a page named _ LogOnPartial. cshtml, which indicates whether the user has logged on. If the user does not log on, the control displays "LogOn" and the link pointing to the LogOn view. If the user has logged on, the control displays a welcome message containing the user name and the link that the user can use to log off.
1 @ if (Request. IsAuthenticated ){
2 <text> welcome to <B> @ Context. User. Identity. Name </B>!
3 [@ Html. ActionLink ("logout", "LogOff", "Account")] </text>
4}
5 else {
6 @: [@ Html. ActionLink ("login", "LogOn", "Account")]
7}
1 @ Html. Partial ("_ LogOnPartial ")
2. Register www.2cto.com
Add a "register" link in the LogOn view. Therefore, each time a user logs on, a link pointing to the Register view is displayed.
1. Enter the user name and password. @ Html. ActionLink ("Register", "Register") if you do not have an account.
3. Change Password
Add a "Change Password" link on the _ LogOnPartial. cshtml page. Therefore, the link to the ChangePassword view is displayed every time the user logs on.
1 [<%: Html. ActionLink ("Change Password", "ChangePassword", "Account") %>]
4. Restrict Access To views
You can specify which parts of an application can only be accessed by authenticated users. To restrict access to a view, you must use the AuthorizeAttribute attribute to mark the operation method for creating the view. You can use the AuthorizeAttribute feature to mark a controller to restrict access to all views of the controller.
Open the HomeController class, find the About operation method, and add the AuthorizeAttribute feature to the About Operation Method declaration.
1 // restrict access to the About view.
2 [Authorize]
3 public ActionResult About ()
4 {
5 return View ();
6}
Click the "About" tab to display the LogOn view, because you must log on to view the About page.
From Yixin yiyu