web.config配置
<authentication mode="Forms">
<forms loginUrl="~/Login/Index" timeout="30" slidingExpiration="true"></forms>
</authentication>
- 1
- 2
- 3
增加一个Attribute类,继承自AuthorizeAttribute
public class CustomAuthorzieAttribute : AuthorizeAttribute
{
private string _controllerName = string.Empty;
private string _actionName = string.Empty;
/// <summary>
/// base.OnAuthorization(filterContext)中会调用AuthorizeCore函数
///
/// 当AuthorizeCore返回false,则会继续调用HandleUnauthorizedRequest进行处理
///
/// 所以OnAuthorization是该类的总入口
///
/// </summary>
/// <param name="filterContext"></param>
public override void OnAuthorization(AuthorizationContext filterContext)
{
_controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
_actionName = filterContext.ActionDescriptor.ActionName;
base.OnAuthorization(filterContext);
}
/// <summary>
/// base.OnAuthorization来调用
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (_controllerName.ToLower() == "login")
{//登陆界面,不用身份认证,直接返回true
return true;
}
if (!httpContext.User.Identity.IsAuthenticated)
{
return false;
}
return true;
}
/// <summary>
/// 当AuthorizeCore返回false时候调用
/// </summary>
/// <param name="filterContext"></param>
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
主要是去除登陆页面的验证判断
在App_Start文件夹中的FilterConfig中增加
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new PermManagerWeb.Controllers.CustomAuthorzieAttribute());
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
登陆页面处理:
[HttpPost]
public ActionResult DoLogin(LoginInfoViewModel loginInfo)
{
if (ModelState.IsValid)
{//输入验证成功
bool bLoginOK = Login.LoginSys(GetDataAccess(), loginInfo.UserName, loginInfo.UserPassword);
if (bLoginOK)
{//登陆成功
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
loginInfo.UserName,
DateTime.Now,
DateTime.Now.AddMinutes(30),
false,
Request.UserHostAddress,
FormsAuthentication.FormsCookiePath);
string strCookie = FormsAuthentication.Encrypt(authTicket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, strCookie);
Response.Cookies.Add(authCookie);
return RedirectToAction("../Main");
}
else
{//登陆失败
return View("Index");
}
}
else
{//输入验证失败
return View("Index");
}
}