我希望得到一些关于我打算用来防止ASP.NET MVC 4应用程序中重复记录的方法的反馈,以及我对用户体验没有的打击效果。
网络表单有六个输入字段和一个保存按钮(以及一个取消按钮),用户最多可以在表格中填写10分钟。
一旦通过帖子提交字段,在使用新Guid作为主键将数据记录到数据库表中之后,页面将在成功/失败时重定向到其他页面。
要停止用户多次按下保存按钮,但允许浏览器在已关闭的连接上重新发布请求,我打算在呈现表单时为新记录主键提供Guid作为隐藏输入字段。 / p>
如果重新发布,或者用户多次按下保存,数据库服务器将拒绝记录的第二个帖子,因为有一个重复的密钥,我可以检查并处理服务器端。
但是这会给我带来更大的问题吗?
答案 0 :(得分:3)
如果您愿意,可以使用某些jQuery阻止客户端双击。
在您的HTML中,将提交按钮设为:
<a id="submit-button"> Submit Form </a> <span id="working-message"></span>
在JavaScript(jQuery)中:
$('#submit-button').click(function() {
$(this).hide();
$('#working-message').html('Working on that...');
$.post('/someurl', formData, function(data) {
//success
//redirect to all done page
}).fail(function(xhr) {
$('#submit-button').show();
$('#working-message').html('Submit failed, try again?');
});
}); // end on click
这会在尝试提交之前隐藏按钮,因此用户无法点击两次。这也显示了进度,并且在失败时允许它们重新提交。您可能需要考虑在上面的代码中添加超时。
另一个选择是使用jquery来抓取表单$('#form-id').submit()
,但是你不能像我已经完成的ajax调用一样轻松地跟踪进度。
修改强> 出于安全原因,我仍然建议从服务器端的角度考虑防止双重提交的方法。
答案 1 :(得分:3)
如果您在表单中使用隐藏的防伪标记(如您所愿),则可以在首次提交时缓存防伪标记,并在需要时从缓存中删除标记,或者在设置后使缓存条目到期时间量。
然后,您将能够针对缓存检查每个请求是否已提交特定表单,如果已提交则拒绝该表单。
您不需要生成自己的GUID,因为在生成防伪令牌时已经完成了此操作。
<强>更新强>
在设计解决方案时,请记住,每个请求都将在其自己的单独线程中异步处理,甚至可能在完全不同的服务器/应用实例上处理。
因此,甚至可以在进行第一次高速缓存条目之前处理多个请求(线程)。要解决此问题,请将缓存实现为队列。在每次提交(发布请求)时,将机器名称/ ID和线程ID写入缓存,以及防伪令牌...延迟几毫秒,然后检查缓存/队列中最旧的条目是否为防伪令牌对应。
此外,所有正在运行的实例必须能够访问缓存(共享缓存)。
答案 2 :(得分:1)
这实际上是MVC(以及其他Web框架)中普遍存在的问题,因此,我将对其进行一些解释,然后提供解决方案。
假设您正在使用表单的网页上。您单击提交。服务器需要一段时间才能做出响应,因此请再次单击它。然后再次。至此,您已经触发了三个单独的请求,服务器将同时处理所有这些请求。但是浏览器只会执行一个响应-第一个响应。
这种情况可以通过以下折线图表示。
┌────────────────────┐
Request 1 │ │ Response 1: completes, browser executes response
└────────────────────┘
┌────────────────┐
Request 2 │ │ Response 2: also completes!
└────────────────┘
┌───────────────────┐
Request 3 │ │ Response 3: also completes!
└───────────────────┘
水平轴表示时间(不按比例)。换句话说,三个请求将按顺序触发,但是只有第一个响应返回到浏览器。其他的都被丢弃了。
这是一个问题。这样的请求并非总是如此,但常常令人讨厌,它们具有副作用。这些副作用可能有所不同,包括增加计数器数量,创建重复记录,甚至多次处理信用卡付款。
现在,在MVC中,大多数POST请求(尤其是具有副作用的POST请求)应使用内置的AntiForgeryToken逻辑为每种形式生成并验证随机令牌。以下解决方案利用了这一优势。
计划:我们丢弃所有重复的请求。这里的逻辑是:缓存每个请求中的令牌。如果它已经在缓存中,则返回一些伪重定向响应,可能带有错误消息。
就我们的折线图而言,这看起来像...
┌────────────────────┐
Request 1 │ │ Response 1: completes, browser executes the response [*]
└────────────────────┘
┌───┐
Request 2 │ x │ Response 2: rejected by overwriting the response with a redirect
└───┘
┌───┐
Request 3 │ x │ Response 3: rejected by overwriting the response with a redirect
└───┘
[*]浏览器执行错误响应,因为它已被请求2和3代替。
请注意以下几点:由于我们根本不处理重复的请求,因此它们会快速执行结果。太快了-他们实际上是先进入来代替第一个请求的响应。
因为我们实际上没有处理这些重复的请求,所以我们不知道将浏览器重定向到何处。如果我们使用虚拟重定向(如/SameController/Index
),则当第一个响应返回到浏览器时,它将执行该重定向,而不是应该执行的操作。由于第一个请求的结果丢失了,因此用户不必理会他们的请求是否实际成功完成。
显然这不理想。
因此,我们修改后的计划是:不仅缓存每个请求的令牌,还缓存响应。这样,我们可以分配实际上应该返回给浏览器的响应,而不是为重复的请求分配任意重定向。
这是使用filter属性在代码中的外观。
/// <summary>
/// When applied to a controller or action method, this attribute checks if a POST request with a matching
/// AntiForgeryToken has already been submitted recently (in the last minute), and redirects the request if so.
/// If no AntiForgeryToken was included in the request, this filter does nothing.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class PreventDuplicateRequestsAttribute : ActionFilterAttribute {
/// <summary>
/// The number of minutes that the results of POST requests will be kept in cache.
/// </summary>
private const int MinutesInCache = 1;
/// <summary>
/// Checks the cache for an existing __RequestVerificationToken, and updates the result object for duplicate requests.
/// Executes for every request.
/// </summary>
public override void OnActionExecuting(ActionExecutingContext filterContext) {
base.OnActionExecuting(filterContext);
// Check if this request has already been performed recently
string token = filterContext?.HttpContext?.Request?.Form["__RequestVerificationToken"];
if (!string.IsNullOrEmpty(token)) {
var cache = filterContext.HttpContext.Cache[token];
if (cache != null) {
// Optionally, assign an error message to discourage users from clicking submit multiple times (retrieve in the view using TempData["ErrorMessage"])
filterContext.Controller.TempData["ErrorMessage"] =
"Duplicate request detected. Please don't mash the submit buttons, they're fragile.";
if (cache is ActionResult actionResult) {
filterContext.Result = actionResult;
} else {
// Provide a fallback in case the actual result is unavailable (redirects to controller index, assuming default routing behaviour)
string controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
filterContext.Result = new RedirectResult("~/" + controller);
}
} else {
// Put the token in the cache, along with an arbitrary value (here, a timestamp)
filterContext.HttpContext.Cache.Add(token, DateTime.UtcNow.ToString("s"),
null, Cache.NoAbsoluteExpiration, new TimeSpan(0, MinutesInCache, 0), CacheItemPriority.Default, null);
}
}
}
/// <summary>
/// Adds the result of a completed request to the cache.
/// Executes only for the first completed request.
/// </summary>
public override void OnActionExecuted(ActionExecutedContext filterContext) {
base.OnActionExecuted(filterContext);
string token = filterContext?.HttpContext?.Request?.Form["__RequestVerificationToken"];
if (!string.IsNullOrEmpty(token)) {
// Cache the result of this request - this is the one we want!
filterContext.HttpContext.Cache.Insert(token, filterContext.Result,
null, Cache.NoAbsoluteExpiration, new TimeSpan(0, MinutesInCache, 0), CacheItemPriority.Default, null);
}
}
}
要使用此属性,只需将其放在[HttpPost]
和[ValidateAntiForgeryToken]
旁边的方法上即可:
[HttpPost]
[ValidateAntiForgeryToken]
[PreventDuplicateRequests]
public ActionResult MySubmitMethod() {
// Do stuff here
return RedirectToAction("MySuccessPage");
}
...并向垃圾邮件发送所有您喜欢的按钮。我已经在几种操作方法上使用了此方法,到目前为止没有任何问题-不管我发送了多少“提交”按钮,都没有重复的记录。
如果有人对MVC实际如何处理请求有更准确的描述(这完全是根据观察和堆栈跟踪编写的),请成为我的客人,我将相应地更新此答案。
最后,感谢@CShark,我以其suggestions作为解决方案的基础。
答案 3 :(得分:0)
您可以在客户端处理它。
创建一个overlay div,一个带display none的css类,一个大的z-index和一个jquery脚本,当用户按下提交按钮时显示div。
答案 4 :(得分:0)
据我了解,您计划在最初渲染页面时将主键保留在隐藏输入中。显然这不是一个好主意。首先,如果你在c#中使用Guid实现,它的字符串并将字符串作为主键并不是一个好主意(See the answer for this SO question)。
您可以通过两种方式解决此问题。首先,在第一次单击时禁用该按钮。其次,在不依赖主键的情况下在代码中构建验证。
答案 5 :(得分:0)
有时,仅在客户端进行处理是不够的。尝试生成形式的哈希码并保存在缓存中(设置到期日期或类似的日期)。
算法类似于:
1-用户发表的帖子
2-生成帖子的哈希值
3-检查缓存中的哈希
4-发布已经在缓存中了吗?引发异常
5-帖子不在缓存中?将新的哈希保存在缓存中,然后将帖子保存在数据库中
示例:
//verify duplicate post
var hash = Util.Security.GetMD5Hash(String.Format("{0}{1}", topicID, text));
if (CachedData.VerifyDoublePost(hash, Context.Cache))
throw new Util.Exceptions.ValidadeException("Alert! Double post detected.");
缓存功能可能是这样的:
public static bool VerifyDoublePost(string Hash, System.Web.Caching.Cache cache)
{
string key = "Post_" + Hash;
if (cache[key] == null)
{
cache.Insert(key, true, null, DateTime.Now.AddDays(1), TimeSpan.Zero);
return false;
}
else
{
return true;
}
}