62,042
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 定义Form验证的接口
/// </summary>
public interface IFormsAuthenticationService
{
void SignIn(string userName, bool createPersistentCookie);
void SignOut();
}
/// <summary>
/// Form验证的实现
/// </summary>
public class FormsAuthenticationService : IFormsAuthenticationService
{
public void SignIn(string userName, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
public class BoperatorController : Controller
{
public IFormsAuthenticationService FormsService { get; set; }
protected override void Initialize(RequestContext requestContext)
{
if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
base.Initialize(requestContext);
}
/// <summary>
/// 验证用户信息
/// </summary>
/// <param name="code">用户名</param>
/// <param name="newpass">密码</param>
/// <returns></returns>
public bool ValidateUser(string code, string newpass)
{
if (String.IsNullOrEmpty(code)) throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(newpass)) throw new ArgumentException("Value cannot be null or empty.", "password");
var boperator = boperatorService.GetBoperator(code, newpass);
if (boperator != null)
return true;
else
return false;
}
public ActionResult LogOn()
{
return View(new LogOnModel());
}
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (ValidateUser(model.code, model.newpass))
{
FormsService.SignIn(model.code, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Account");
}
}
else
{
ModelState.AddModelError("", "用户名或密码错误!");
}
}
return View(model);
}
public ActionResult LogOff()
{
FormsService.SignOut();
return RedirectToAction("LogOn", "Boperator");
}
}
public MvcApplication()
{
AuthorizeRequest += new EventHandler(MvcApplication_AuthorizeRequest);
}
void MvcApplication_AuthorizeRequest(object sender, EventArgs e)
{
IIdentity id = Context.User.Identity;
if (id.IsAuthenticated)
{
string[] roles = new string[1];
roles[0] = id.Name;
Context.User = new GenericPrincipal(id, roles);
}
}
[Authorize]
/// <summary>
/// 显示所有账户信息
/// </summary>
/// <returns>账户信息列表</returns>
public ActionResult Index()
web.confing中加入
<authentication mode="Forms">
<forms loginUrl="~/Home/index" timeout="2880" />
</authentication>
if (new account.Data.Bll().Login(username, possWord))//验证身份
{
FormsAuthentication.SetAuthCookie(username, false);//验证通过
return RedirectToAction("index", "bc");
}
[Authorize]
/// <summary>
/// 显示所有账户信息
/// </summary>
/// <returns>账户信息列表</returns>
public ActionResult Index()