I am using ASP.NET profiles with allowAnonymous=”true”. I am NOT using ASP.NET membership. I recently took a hard look at the aspnetdb database and noticed that although my site gets 600-800 unique visitors daily, there are 4000-5000 “users” being created in the database.
Clearly what is happening here is the users with cookies disabled end up creating a record for every request.
My question: How do I prevent user and profile database records from being created if the client doesn’t support cookies or has them disabled?
After a lot of research and trial and error, I discovered a solution to this issue. However, this solution does not work for the first request that the user makes because it is impossible to determine if a user supports cookies from only one request.
I came up with a clever solution that uses AJAX to make a second (invisible) request to the server in order to write settings to the profile on the first request, but only if cookies and JavaScript are enabled. Of course, if you are not storing any profile settings on the initial request, it is not necessary to use this. See my other post for complete details.
Simply put, this class prevents the profile from being written to or saved if the profile is anonymous and the anonymous cookie hasn’t been received from the browser yet.
In order to use this class, put it into the App_Code directory and add an “inherits” attribute to the profile element in the web.config file as follows:
ASP.NET will then inherit the ProfileCommon class from this one when it is automatically generated.
Note that the AnonymousCookieName and IsAnonymousCookieStored properties were made public shared so they can be used anywhere else in the project like this:
This can save some CPU cycles from executing code that doesn’t need to run if the user rejected the anonymous cookie, but isn’t strictly necessary because the new profile class will check anyway.
There is also another bug fix included in this sample – the original profile class will be “Dirty” if you set a property to the same value it already contains, which will cause it to update the database even though nothing has changed. There is a check for this condition in the overloaded SetPropertyValue method which fixes this problem.
Reference: ProfileBase Class (MSDN)