首页 新闻 会员 周边

asp.net mvc项目身份认证问题

0
[已解决问题] 解决于 2018-10-05 10:58

项目新建的时候 有身份认证,和我自己创建一个类 继承自AuthorizeAttribute 重写OnAuthorized方法 有什么区别,我是根据session 是否为null判断 用户有没登陆, 感觉微软那个太臃肿了点,一般项目里 自己写的比较多 ,还是直接用自带的

mvc
AliceBaby的主页 AliceBaby | 初学一级 | 园豆:184
提问于:2018-09-02 22:26
< >
分享
最佳答案
0

在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();
        }
    }


}
奖励园豆:5
happydaily | 菜鸟二级 |园豆:301 | 2018-09-03 08:18
其他回答(1)
0

自己写个过滤器比较好

ice.ko | 园豆:90 (初学一级) | 2018-09-04 16:31
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册