废旧网站那个做的最好网站模板出售
废旧网站那个做的最好,网站模板出售,wordpress使用什么语言,网络工程师证书考试时间咨询区 Guilherme Ferreira#xff1a;我通过 post 方式向我的一个webapi中提交数据#xff0c;然后插入到数据库中#xff0c;在 ui端#xff0c;当用户点击某一个 button 之后#xff0c;代码会将 button 禁用#xff0c;但因为某些原因#xff0c;点击按钮的速度比禁… 咨询区 Guilherme Ferreira我通过 post 方式向我的一个webapi中提交数据然后插入到数据库中在 ui端当用户点击某一个 button 之后代码会将 button 禁用但因为某些原因点击按钮的速度比禁用按钮的函数还要快这就造成了post两次的情况也就插入了两条同样的数据。在客户端我用 axios 来做 post 提交请问我如何在 server 端规避这种事情回答区 Christian Gollhardt前段时间刚好遇到了这个场景我创建了一个 ActionFilter然后使用了 Anti Fogery Token 参考如下代码首先启用 session。services.ConfigureCookiePolicyOptions(options {// This lambda determines whether user consent for non-essential cookies is needed for a given request.options.CheckConsentNeeded Context false;options.MinimumSameSitePolicy SameSiteMode.None;});services.AddMemoryCache();services.AddSession(options {// Set a short timeout for easy testing.options.IdleTimeout TimeSpan.FromMinutes(10);options.Cookie.HttpOnly true;// Make the session cookie essentialoptions.Cookie.IsEssential true;});然后就可以 use 了。app.UseSession();接下来定义一个防重复提交的 Attribute 。[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class PreventDoublePostAttribute : ActionFilterAttribute
{private const string UniqFormuId LastProcessedToken;public override async void OnActionExecuting(ActionExecutingContext context){IAntiforgery antiforgery (IAntiforgery)context.HttpContext.RequestServices.GetService(typeof(IAntiforgery));AntiforgeryTokenSet tokens antiforgery.GetAndStoreTokens(context.HttpContext);if (!context.HttpContext.Request.Form.ContainsKey(tokens.FormFieldName)){return;}var currentFormId context.HttpContext.Request.Form[tokens.FormFieldName].ToString();var lastToken context.HttpContext.Session.GetString(UniqFormuId);if (lastToken.Equals(currentFormId)){context.ModelState.AddModelError(string.Empty, Looks like you accidentally submitted the same form twice.);return;}context.HttpContext.Session.Remove(UniqFormuId);context.HttpContext.Session.SetString(UniqFormuId, currentFormId);await context.HttpContext.Session.CommitAsync();}}然后在需要该验证规则的 Action 上进行标注。[HttpPost]
[PreventDoublePost]
public async TaskIActionResult Edit(EditViewModel model)
{if (!ModelState.IsValid){//PreventDoublePost Attribute makes ModelState invalid}throw new NotImplementedException();
}关于如何生成 Anti Fogery Token可以看下msdn: https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?viewaspnetcore-2.2#javascript点评区 这是一个非常常见的需求除了这种做法通常用带有过期时间的cache来做也是可以的比如 3s 内只能有一个请求。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/88821.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!