通过制作一个登陆小案例搭建 MVC + 三层
@ViewBag.Title
User Management System
@if (Request.IsAuthenticated) //如果登陆成功
{
Current ID: @Context.User.Identity.Name //获取当前登录用户
}
else
// 未登录状态
{
}
Pls login first! //提示需要先登录
@RenderBody()
注意:需要使用Request.IsAuthenticated 身份验证,需要在Web.Config 下添加如下代码
public class AccountController : Controller
{
// GET: Account
public ActionResult Index()
{
return View();
}
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(AccountEntity account)
{
if (new Bll.AccountManageBll().LoginCheck(account))
{
FormsAuthentication.SetAuthCookie(account.LogID, true);
return RedirectToAction("Index", "Home");
}
else
{
ViewBag.msg = "LogID or Password error.";
return View();
}
}
public ActionResult LogOut()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index","Home");
}
}
@using Model
@model AccountEntity
@{
ViewBag.Title = "Login";
Layout = "~/Views/Shared/_LoginPartial.cshtml";
}
@using (Html.BeginForm("Login", "Account", FormMethod.Post))
{
Log In
Login ID @Html.TextBoxFor(u => u.LogID)
@Html.ValidationMessageFor(u => u.LogID, "", new { style = "color:#F00;font-size:10px" })
Password @Html.PasswordFor(u => u.Password)
@Html.ValidationMessageFor(u => u.Password, "", new { style = "color:#F00;font-size:10px" }) //校验不能为空
@ViewBag.msg
}
public class AccountEntity
{
[Required(ErrorMessage ="LogID cann't be empty!")] //Required 验证
public string LogID { get; set; }
[Required(ErrorMessage = "Password cann't be empty!")] //Required 验证
public string Password { get; set; }
public AccountEntity() { } //无参构造函数
public AccountEntity(string ID,string Pwd) //有参构造函数 为了测试数据
{
LogID = ID;
Password = Pwd;
}
}
【使用数据库才需要使用 本实例测试数据在BLL层】
///
/// 获取用户信息
///
///
public List GetAccountInfo()
{
string sqlStr = @"ProcSelAccount"; //存储过程名
List accountList = new List();
using (SqlDataReader reader = SqlHelper.ExecReader(sqlStr)) //SqlHelper: SQL帮助类
{
while (reader.Read())
{
AccountEntity account = BuildSubject(reader);
accountList.Add(account);
}
}
return accountList;
}
public AccountEntity BuildSubject(SqlDataReader reader)
{
AccountEntity account = new AccountEntity();
account.LogID = reader.GetString(0);
account.Password = reader.GetString(1);
public bool LoginCheck(AccountEntity account)
{
bool flag = false;
// List accountList = new AccountServiceDal().GetAccountInfo(); //校验数据库中用户数据,需使用此代码
//Test Account Data
List accountList = new List() //增加两条用户数据
{
new AccountEntity("Jarvis","ABC123"),
new AccountEntity("Admin","admin123")
};
foreach (AccountEntity accountInfo in accountList)
{
if(accountInfo.LogID == account.LogID && accountInfo.Password == account.Password)
{
flag = true;
}
}
return flag;
}