The Poll control offers a built-in security mechanism, which can be used to prevent users from voting multiple times.
Use the
AllowedVotesPerUser property to indicate the number of times a user is allowed to vote and the
SecurityMethod property to indicate how the security will be handled:
-
Cookies - a cookie will be created when a user votes. The advantage of this security method is that it doesn't require any
coding to be performed by developers. The drawback is that the cookies are stored on the client-side (browser), and thus the users can vote
multiple times if they clear their cookies, use a different browser or a different computer.
Use this method for simple polls where the results are not mission-critical. This is the default security method employed by the Poll.
-
Session - a session variable will be created when a user votes. The advantage of this security method is that it doesn't require any
coding to be performed by developers. The drawback is that the sessions are lost when the browser is closed, and thus the users can vote
multiple times if they close their browser, use a different browser or a different computer.
Use this method for simple polls where the results are not mission-critical.
-
Custom - the security checks will be performed by the developers, by handling the SecurityChecking event.
This approach allows developers to check whether a user is allowed to vote using various approaches, like comparing the user's identity
with the history of votes from the database, checking the user's IP address, etc. By using this security method the poll results can be more reliable
and thus it is recommended for applications where the results are important.
This example showcases the use of the
Custom security method.
AllowedVotesPerUser is set to 1,
so you will be able to vote only once. You will be able to vote only once no matter what,
because the user identity (User ID) is searched in the database to see whether the current user already voted for this poll.
For this sample, we hardcoded the User ID in the code behind class of the page, but in a real application you'll probably end up using the
user identity provided by the ASP.NET built-in authetication / authorization features (or the one provided by any custom auth framework that you might be using).
We used the
Voted event to store the ID of the user that performed the vote, along with the selected answer; the
SecurityChecking event was used to check whether the current user is allowed to vote.