我在 .NET Core REST API 中使用 POST 在数据库中插入数据。
在我的客户端应用程序中,当用户单击一个按钮时,我会禁用该按钮。但有时,由于某些原因,按钮的点击可能比禁用按钮的功能更快。这样,用户可以双击按钮,POST 将被发送两次,插入数据两次。
要执行 POST,我在客户端使用 axios。但是我怎样才能在服务器端避免这种情况呢?
最佳答案
我前段时间遇到过这种情况。我为它创建了一个 Action 过滤器,它使用了 Anti Fogery Token。 :
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class PreventDoublePostAttribute : ActionFilterAttribute
{
private const string TokenSessionName = "LastProcessedToken";
public override void OnActionExecuting(ActionExecutingContext context)
{
var antiforgeryOptions = context.HttpContext.RequestServices.GetOption<AntiforgeryOptions>();
var tokenFormName = antiforgeryOptions.FormFieldName;
if (!context.HttpContext.Request.Form.ContainsKey(tokenFormName))
{
return;
}
var currentToken = context.HttpContext.Request.Form[tokenFormName].ToString();
var lastToken = context.HttpContext.Session.GetString(TokenSessionName);
if (lastToken == currentToken)
{
context.ModelState.AddModelError(string.Empty, "Looks like you accidentally submitted the same form twice.");
return;
}
context.HttpContext.Session.SetString(TokenSessionName, currentToken);
}
}
简单地在你的方法上使用它:
[HttpPost]
[PreventDoublePost]
public async Task<IActionResult> Edit(EditViewModel model)
{
if (!ModelState.IsValid)
{
//PreventDoublePost Attribute makes ModelState invalid
}
throw new NotImplementedException();
}
请确保您生成了防伪 token ,请参阅有关 Javascript 工作原理的文档或 Angular .
关于c# - 使用 .NET Core 避免重复的 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55286021/