4

I'm not talking about asp.net membership.

For each logged user I want to cache some properties like status or the number of friend requests, from the db.

I can create custom class which would do it but I thought it will be better to extend the existing User.Identity property.
Something like this:

Label1.Text = User.Identity.Status;

It is possible?

Adir
  • 1,423
  • 3
  • 19
  • 32

2 Answers2

5

It is possible by defining your own IIdentity (and possibly IPrincipal too) and constructing this when creating the IPrincipal for the HTTP request. I believe the correct place to do this is when the PostAuthenticateRequest event is raised.

The answers on this other stackoverflow question explain how to do it - ASP.NET set custom identity or principal (it says for MVC but both go through the same processing pipeline).

Community
  • 1
  • 1
Russ Cam
  • 124,184
  • 33
  • 204
  • 266
3

Based on your example, I believe you should be caching things like status and number of friend requests in the session data.

The possible downside of using the Identity for this caching is that, if I am not mistaken, each request results in a new Identity instance being created. So for each request you will need to repopulate these Identity values from somewhere, either the DB or some place that you have already cached the data anyway.

Chris Taylor
  • 52,623
  • 10
  • 78
  • 89
  • Thanks for the response. So I should simply create my own class that cache those properties? What would better session or server cache? – Adir Jul 31 '10 at 11:19
  • @Adir, Depends on your requirements. When the session expires you no longer need the cached data so it will clean-up automatically with the session. Also if you are targetting a web farm the session will migrate between servers (assuming you are using external session state) and the cached data will be available where you need it when you need it. Server cache would of course work well, but the lifetime would be independent of the session lifetime, which does have the advantage that the logic to refresh the cache is quite simple, if the data is not in the cache then reread it, eg. every 10min. – Chris Taylor Jul 31 '10 at 12:41
  • Each request does indeed reconstruct the `IPrincipal` and `IIdentity` from the FormsAuthentication ticket. You could have an `IIdentity` with a method that simply retrieves the number of friends requests from a source, be it in session or from another datasource and this way, you're not storing any of that data in the actual authentication cookie. – Russ Cam Jul 31 '10 at 19:18