Click here to Skip to main content
15,911,139 members
Please Sign up or sign in to vote.
4.67/5 (2 votes)
See more:
i am using session["Admin"] = id of an admin picked from database, i have assigned few pages to it that if this session id is not null then allow to see pages but if it is null then don't allow user to view that page but problem is that i am doing this on every page to check if it is null or not. Is there any way to mention it once and work for all application ? like whenever it is empty then redirect to any page or this page.

i am using mVC 3 with asp.net 4 C#
Posted
Comments
Govindaraj Rangaraj 14-Feb-14 4:23am    
Are you taking about your cshtml views? How about puting them in _layout or some other shared view?

1 solution

Instead of using Session Variables, you can use custom membership in mvc using Forms Authentication. And you can use the attribute '[Authorize(Roles = "Admin")] on controller or action methods in MVC. If user was not an admin then it automatically redirects to login page.


Custom Membership
C#
FormsAuthentication.SetAuthCookie(user.Id + "." + role.Name, false);



protected void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs e)
        {
            if (FormsAuthentication.CookiesSupported == true)
            {
                if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
                {
                    string[] text=(FormsAuthentication.Decrypt(
                        Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name).Split('.');
                    string userId = text[0];
                    string role = text[1];

                    e.User = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity(userId, "Forms"), role.Split(';'));
                }
            }
        }



Usage
C#
[Authorize(Roles = "Admin")]
   public class AdminController : Controller
   {
//action 
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900