Wednesday, November 5, 2008

Obtaining the Current User from ASP.Net's Membership Infrastructure

The extensive membership (& roles) library available to ASP.Net developers is very powerful but also bewildering at times. Case in point is how to obtain the current username. Having just implemented it in a sophisticated multi-user app, I've been forced to really put it to the test.

Depending on the situation, the current username can be obtained in these different ways:
  1. Login1.Username
  2. Page.User.Identity.Name
  3. HttpContext.Current.User.Identity.Name
Why the need for all these different approaches to get the same data? Well, here are some examples:
  • If you need it in the "Logged_In" event handler, #2 & #3 aren't accessible.
  • If you need it outside of your Login page, #1 isn't accessible.
  • If you need it outside the context of a Page, such as when an asynchronous AJAX event is fired, #2 isn't accessible.
So flexibility is the key here. And knowledge of the different paths to the same answer is more than a little useful!

No comments:

Post a Comment