这是一个多部分的答案,但您需要做的是:
- 在您的登录页面上,有一个指向您的登录控制器的表单
- 在您的帐户控制器中,处理登录操作
- 在您的布局页面中,您可以像这样引用当前登录的用户
示例如下:
1) 您的登录页面
@using(Html.BeginForm("Logon", "Account")) {
@Html.TextBox("username")
@Html.Password("password")
}
2)您的登录/帐户控制器
public class AccountController : Controller {
public ActionResult Logon(string username, string password) {
// login logic here
// save the username
Session["Username"] = username;
// Or you can reference user the user identity
Session["Username"] = User.Identity.Name;
// Redirect somewhere when you're done
return Redirect("LoggedInPage", "Home");
}
}
3)在你的 _Layout 标题中
@if(HttpContext.User.Identity.IsAuthenticated) {
@Session["Username"]
// or
@HttpContext.User.Identity.Name
} else {
<div>You should log in!</div>
}