Create Model LoginPageViewModel.cs
using System;
using System.Collections.Generic;using System.Linq;using System.Web;namespace CustomSecurityExampleMVC30.Models
{ public class LoginPageViewModel { public string Username { get; set; } public string Password { get; set; } public string ErrorMessage { get; set; } }}Create Account/Login.cshtml View
@model CustomSecurityExampleMVC30.Models.LoginPageViewModel
@{
ViewBag.Title = "Login"; Layout = "~/Views/Shared/_Layout.cshtml";}@using (Html.BeginForm()){ <fieldset style="width: 280px;"> <legend>Login</legend> <p> <label> username</label> @Html.TextBoxFor(x => x.Username) </p> <p> <label> Password</label> @Html.TextBoxFor(x => x.Password) </p> <p> <input type="submit" value="login" /> </p> </fieldset>}Create AccountController.cs Controller
using System;
using System.Collections.Generic;using System.Linq;using System.Web;using CustomSecurityExampleMVC30.Models;using System.Web.Mvc;namespace CustomSecurityExampleMVC30.Controllers
{ public class AccountController : BaseController { public ActionResult Login() { var vm = new LoginPageViewModel { Username = "Username", Password = "Password" };return View(vm);
}[HttpPost]
public ActionResult Login(LoginPageViewModel viewModel) { if (string.IsNullOrEmpty(viewModel.Username)|| string.IsNullOrEmpty(viewModel.Password)) { viewModel.ErrorMessage = "Please provide your username and password"; return View(viewModel); }SimpleSessionPersister.Username = viewModel.Username;
return RedirectToAction("Index", "Home");
} }}Create IndexPageViewModel.cs Model
using System;
using System.Collections.Generic;using System.Linq;using System.Web;namespace CustomSecurityExampleMVC30.Models
{ public class IndexPageViewModel { public string CurrentUsername { get; set; } //51aspx.com下载 }}
Create View Index.cshtml
@model CustomSecurityExampleMVC30.Models.IndexPageViewModel
@{
ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml";}<h2>Index</h2>
<h3>Welcome, @Model.CurrentUsername!</h3>
Create Controller HomeController.cs
using CustomSecurityExampleMVC30.Models;
using System.Web.Mvc;namespace CustomSecurityExampleMVC30.Controllers
{ public class HomeController : BaseController { [Authorize] public ActionResult Index() { return View( new IndexPageViewModel { CurrentUsername = this.User.Identity.Name}
);//51aspx.com下载
} }}
set Account/Login.cshtml as start page in web.config
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" /> </authentication></system.web>