限制用户只填写一次表单
本文关键字:一次 表单 用户 | 更新日期: 2023-09-27 18:08:36
我希望创建一个简单的web表单,我想"劝阻"用户多次填写表单。表单的指标用于统计分析,每次用户填写并重新提交表单时,结果集通常会发生变化,因此需要进行分析。
虽然我们不想阻止重试(知道重试也是有价值的信息),但我们确实想警告用户:"嘿,看起来您最近填写了这个。你确定要再填写一遍吗?"
这里的警告是,我们希望尽量减少收集的个人身份信息的数量。
用客户端IP存储cookie是最好/最简单的方法吗?或者是否有一种简单的方法将IP服务器端缓存xx时间,这样我们就可以进行比较,说,嘿,我认为这个家伙今天早些时候试图访问我。
Cookie具有恒定值应该足够了,甚至不需要IP。如果用户没有清除cookie,您就会知道用户已经填写了表单。
我以前使用过的一个简单的解决方案是在用户填写的HTML表单中放置一个不可见的时间戳。如果你两次提交了相同的时间戳,你就知道这是一次重新提交。
如果你担心被篡改,你可以混合/加密时间戳。
这也可以是一个随机的唯一标识符,我选择了一个时间戳,以便知道用户填写表单花了多长时间(大致)。
这基本上就像一个会话cookie,但可能被认为是更"私人"的,因为客户端的计算机没有什么要记住的,所以它不能像一些跟踪cookie广告网站那样使用。
这里有两个问题:用户多次单击提交按钮,以及用户在另一个时间点填写表单。
对于第二个我可以看到两个相当简单的解决方案会推荐一个会话cookie,只是cookie用户机器,不让他们看到表单再次,或要求一块信息,如电子邮件地址,然后检查在数据库中,如果它以前使用过,如果这样,忽略新的表单细节。
对于多表单提交,您可以使用以下代码,这将禁用按钮onclick。
//
// Disable button with no secondary JavaScript function call.
//
public static void DisableButtonOnClick(Button ButtonControl)
{
DisableButtonOnClick(ButtonControl, string.Empty);
}
// Disable button with a JavaScript function call.
//
public static void DisableButtonOnClick(Button ButtonControl, string ClientFunction)
{
var sb = new StringBuilder(128);
// If the page has ASP.NET validators on it, this code ensures the
// page validates before continuing.
sb.Append("if ( typeof( Page_ClientValidate ) == 'function' ) { ");
sb.Append("if ( ! Page_ClientValidate() ) { return false; } } ");
// Disable this button.
sb.Append("this.disabled = true;");
// If a secondary JavaScript function has been provided, and if it can be found,
// call it. Note the name of the JavaScript function to call should be passed without
// parens.
if (!String.IsNullOrEmpty(ClientFunction))
{
sb.AppendFormat("if ( typeof( {0} ) == 'function' ) {{ {0}() }};", ClientFunction);
}
// GetPostBackEventReference() obtains a reference to a client-side script function
// that causes the server to post back to the page (ie this causes the server-side part
// of the "click" to be performed).
sb.Append(ButtonControl.Page.GetPostBackEventReference(ButtonControl) + ";");
// Add the JavaScript created a code to be executed when the button is clicked.
ButtonControl.Attributes.Add("onclick", sb.ToString());
}