项目新建的时候 有身份认证,和我自己创建一个类 继承自AuthorizeAttribute 重写OnAuthorized方法 有什么区别,我是根据session 是否为null判断 用户有没登陆, 感觉微软那个太臃肿了点,一般项目里 自己写的比较多 ,还是直接用自带的
在App_Start文件夹中找到FilterConfig.cs,添加如下代码
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CustomExceptionAttribute());
filters.Add(new CheckLoginAndRight());
}
class CheckLoginAndRight : ActionFilterAttribute
{
const string User_InfoKey = "Customer_User";
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!IsDefined(filterContext, typeof(SkipLoginCheckAttribute)))
{
if (!IsLogined())
{
filterContext.Result = new RedirectResult("/Account/LoginOn");
}
else if (!IsDefined(filterContext, typeof(SkipAuthorityCheckAttribute)))
{
string strAreaName = filterContext.RouteData.DataTokens["area"].ToString().ToLower();
string strContrllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();
string strActionName = filterContext.ActionDescriptor.ActionName.ToLower();
//string strHttpMethod = filterContext.HttpContext.Request.HttpMethod;
if (!IsAuthority(strAreaName, strContrllerName, strActionName))
{
filterContext.Result = new RedirectResult("/Account/NoAuthority");
}
}
}
}
bool IsDefined(ActionExecutingContext filterContext ,Type type)
{
return filterContext.ActionDescriptor.IsDefined(type, false)
|| filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(type, false);
}
bool IsLogined()
{
//1.验证用户是否登陆(Session && Cookie)
if (HttpContext.Current.Session[User_InfoKey] == null)
{
if (HttpContext.Current.Request.Cookies[User_InfoKey] == null)
{
return false;
}
}
return true;
}
bool IsAuthority(string area, string controller, string action)
{
return true;
}
}
class CustomExceptionAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
filterContext.Result = new HttpNotFoundResult();
}
}
}
自己写个过滤器比较好