问题描述:

I am building a asp.net web application (framework 4) and wanted to developed a class that holds basic customer information (customer id, email, phone, address info, customer accounts etc) which should be

available to access through out the website pages so that I don't have store customer id some where (session etc) and make call to DB whenever I need some info about that customer.

I wanted to make a call to DB only once when users logs in to portal and get his/her basic info and store it in form of a class.

can any one tell how to develope such type fo class and where/how to store it to make it avail to all the pages?

网友答案:

Once user successfully logged in, make a single call to DB to retrieve the current Customer object and save it to the Session. Don't just think that you will be misusing the server's memory. The object would be less than 500 bytes and if you have 1000 live sessions it's just less than 500 KB of your server's memory.

You may also consider Cache typed to User ID and retrieve Customer object along.

You may also save the Customer object to ViewState and that wouldn't take any memory on the server.

It's very easy to access Session\ Cache\ ViewState from any page.

For Session:

protected void Page_Load(object sender, EventArgs eventArgs)
{
    Customer customer = Session["customer"] as Customer;
}

private void LoginSuccess(int customerID) {
    Customer customer = _customerRepository.GetById(customerID);
    Session["customer"] = customer;
}

**For ViewState, it's just same as Session - just replace Session with ViewState.

If you want to store it in Cache then use

HttpContext.Current.Cache.Insert("customer" + customerId, customer, new CacheDependency("customer" + customerId), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);

And you can access the Cache item like this:

HttpContext.Current.Cache["customer" + customerID]

Hope this helps!

相关阅读:
Top