简体   繁体   中英

Where to place the access privileged

I am developing an application in MVC4. In that I have various types of user and each user carry different access privileged. Depending upon the access user carry application will generate the view accordingly. This Access will be give to user at the time of creation.

I have store this access privileged in Database. My Problem is that every time user did something I have to check the whether it has access or not, for that every time I need to take it from database but I don't want to do. I wish do that to keep in a xml file but when multiple user use it will get over write which do malfunctioning.

I want to know that what is the great place to keep those details so that it will be available me all the time through out the project.

You can store this information in the global Application Cache which is accessible to all sessions of your web application. If you want to store the data per session then can you should consider storing your data in the Session.

Here is a link to techniques and best practices for caching in .net.

Session caching is probably more useful in your case since the data is for a logged in user.

Stuffing user data in the session is pretty straightforward. Here is an example of how I would envision storing data about a user.

public class MySession
{
    private const string _SessionName = "__MY_SESSION__";

    private MySession(){}

    public MyUser CurrentUser { get; set; }

    public static MySession Current
    {
        get
        {
            MySession session =(MySession)HttpContext.Current.Session[_SessionName];
            if (session == null)
            {
                session = new MySession();                    
                HttpContext.Current.Session[_SessionName] = session;
            }
            return session;
        }
    }

    public void Clear()
    {
        HttpContext.Current.Session.Clear();
        HttpContext.Current.Session.Abandon();
    }
}

You can then use this class in some static helper class that is accessible to server side methods.

public static MyAppClass
{
    public static MySession Session { get { return MySession.Current; } }
}

And then in your controllers you simply make a call similar to:

public ActionResult Login()
{
    MyUser user=GetUserFromDatabase();
    MyAppClass.Session.CurrentUser=user;
}


public ActionResult SomMethod()
{
    MyUser loggedInUser=MyAppClass.Session.CurrentUser;
    if(loggedInUser.CanAccess(something))
    {
      ....
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM