[MVC 5] 快速加入 FormAuthenticate 登入
導覽
- web.config 設定 authentication 區塊
- 加入 Controllers/AccountController
- 加入檢視 Views/Account/Login.cshtml
- 加入AuthorizeAttribute 於 Controllers/HomeController
1. web.config 設定 authentication 區塊
...
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms name=".MyMVCAuth" loginUrl="Login" defaultUrl="Home"></forms>
</authentication>
...
2. 加入 Controllers/AccountController
public class AccountController : Controller
{
[Route("Login")]
[HttpPost()]
public ActionResult Login(string account)
{
FormsAuthentication.SetAuthCookie(account, true);
return RedirectToAction("Index", "Home");
}
[Route("Logout")]
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Account");
}
}
3. 加入檢視 Views/Account/Login.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Login</title>
</head>
<body>
<form id="form1" method="post" action='@Url.Action("Login")'>
<div class="login_box">
<div class="row">
<h1>
<img src="~/Content/CSS/img/logo.jpg" />
</h1>
</div>
<div class="row">
<label>帳號:</label>
<input type="text" id="account" />
</div>
<div class="row">
<input type="submit" id="loginAction" value="登入" />
</div>
</div>
</form>
</body>
</html>
4. 加入AuthorizeAttribute 於 Controllers/HomeController
public class HomeController : Controller
{
[Authorize]
public ActionResult Index()
{
return View();
}
}