//检查登录
public class CheckLoginFilter : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
//不验证属性则只需取值
if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
{
if (filterContext.HttpContext.Request.Cookies["token"] != null) {
string token = filterContext.HttpContext.Request.Cookies["token"].Value;
if (token != "")
{
//如果cookie存在则判断Session
if (filterContext.HttpContext.Session[token] == null)
{
GuserService bll = new GuserService();
GuserDTO model = bll.GetUserByToken(token);
if (model == null) {
return;
}
filterContext.HttpContext.Session[token] = model;
filterContext.Controller.ViewBag.UserName = model.userName;
filterContext.Controller.ViewBag.Uid = model.id;
}
else
{
GuserDTO model = (GuserDTO)filterContext.HttpContext.Session[token];
filterContext.Controller.ViewBag.UserName = model.userName;
filterContext.Controller.ViewBag.Uid = model.id;
return;
}
}
else {
return;
}
}
return;
}
else {
string actionName = filterContext.ActionDescriptor.ActionName;
string ctrlName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
string returnUrl = "?returnUrl=/" + ctrlName + "/" + actionName;
//判断储存token的Cookie存在与否
if (filterContext.HttpContext.Request.Cookies["token"] == null)
{
filterContext.Result = new RedirectResult("/Home/Login"+returnUrl);
}
else {
string token = filterContext.HttpContext.Request.Cookies["token"].Value;
if (token == "")
{
filterContext.Result = new RedirectResult("/Home/Login"+returnUrl);
}
else
{
//如果cookie存在则判断Session
if (filterContext.HttpContext.Session[token] == null)
{
GuserService bll = new GuserService();
GuserDTO model = bll.GetUserByToken(token);
filterContext.HttpContext.Session[token] = model;
filterContext.Controller.ViewBag.UserName = model.userName;
filterContext.Controller.ViewBag.Uid = model.id;
}
else {
GuserDTO model = (GuserDTO)filterContext.HttpContext.Session[token];
filterContext.Controller.ViewBag.UserName = model.userName;
filterContext.Controller.ViewBag.Uid = model.id;
}
}
}
}
}
}