.net core 中如何有效屏蔽重复提交
生活随笔
收集整理的這篇文章主要介紹了
.net core 中如何有效屏蔽重复提交
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
咨詢區
Guilherme Ferreira:
我通過 post 方式向我的一個webapi中提交數據,然后插入到數據庫中,在 ui端,當用戶點擊某一個 button 之后,代碼會將 button 禁用,但因為某些原因,點擊按鈕的速度比禁用按鈕的函數還要快,這就造成了post兩次的情況,也就插入了兩條同樣的數據。
在客戶端我用 axios 來做 post 提交,請問我如何在 server 端規避這種事情?
回答區
Christian Gollhardt:
前段時間剛好遇到了這個場景,我創建了一個 ActionFilter,然后使用了 Anti Fogery Token ,參考如下代碼:
首先啟用 session。
services.Configure<CookiePolicyOptions>(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?Task<IActionResult>?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?view=aspnetcore-2.2#javascript
點評區
這是一個非常常見的需求,除了這種做法,通常用帶有過期時間的cache來做,也是可以的,比如 3s 內只能有一個請求。
總結
以上是生活随笔為你收集整理的.net core 中如何有效屏蔽重复提交的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 02Prism WPF 入门实战 - 建
- 下一篇: Fiddler抓包一键生成调用代码