Overriding AuthorizeAttribute in MVC 4

后端 未结 2 398
难免孤独
难免孤独 2020-12-14 18:51

In my application, I want to redirect the authorized user to update their profile page until they have provided required information. If they update profile, then the

2条回答
  •  情歌与酒
    2020-12-14 19:30

    I've taken this code and added some of my own changes, namely to check if the currently logged in user has a session state on the server, they're not as expensive as they used to be!

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var authorized = base.AuthorizeCore(httpContext);
            if (!authorized && !Membership.isAuthenticated())
            {
                // The user is not authorized => no need to go any further
                return false;
            }
    
            return true;
        }
    }
    public class Membership
    {
        public static SystemUserDTO GetCurrentUser()
        {
            // create a system user instance
            SystemUserDTO user = null;
    
            try
            {
                user = (SystemUserDTO)HttpContext.Current.Session["CurrentUser"];
            }
            catch (Exception ex)
            {
                // stores message into an event log
                Utilities.Log(ex.Message, System.Diagnostics.EventLogEntryType.Warning);
    
            }
            return user;
        }
    
        public static bool isAuthenticated()
        {
            bool loggedIn = HttpContext.Current.User.Identity.IsAuthenticated;
            bool hasSession = (GetCurrentUser() != null);
            return (loggedIn && hasSession);
        }
    }
    

提交回复
热议问题