有这样一个场景
在登录页面中 LogOn.aspx提供用户登录。
登录成功转到 Index.aspx,如果用户没有登录 则不能直接访问Index.aspx
我早web.config 这样配置:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" defaultUrl="~/User/Index" protection="All"/>
</authentication>
然后在 控制器里 Index()方法前 放[Authorize]
我在登录的控制器里 LogOn() 怎样写代码 实现该功能
public IFormsAuthenticationService FormsService { get; set; }
public IMembershipService MembershipService { get; set; }
protected override void Initialize(RequestContext requestContext)
{
if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
base.Initialize(requestContext);
}
// **************************************
// URL: /Account/LogOn
// **************************************
public ActionResult LogOn()
{
return View();
}
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Account");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
// **************************************
// URL: /Account/LogOff
// **************************************
public ActionResult LogOff()
{
FormsService.SignOut();
return RedirectToAction("Index", "Home");
}
mvc自动生成代码中就有。
web.config设置了就可以吧
LogOn写你自己登陆的逻辑就可以了