c# - 使用 .NET Core 避免重复的 POST

标签 c# .net asp.net-core

我在 .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/

相关文章:

c# - 如何使用 xUnit 对 C# 事件进行单元测试

c# - Owin 中间件 VS WebAPI DelegatingHandler

c# - Serilog RavenDb 接收器无法在 asp.net 5 应用程序中工作

c# - 部署预编译的 ASP.net 网站项目

c# - 如何从不同线程更新ASP.NET Web表单?

c# - 长时间停顿的并行任务

c# - C#中如何四舍五入到任意数字?

c# - 当窗体具有许多下拉列表控件时,C#.net 窗体调整大小缓慢

c# - Moq,Setup() 和 Returns() 之间的类型不匹配

c# - ASP.NET 5 MVC 6 : How to configure startup to send a html file when not on any mvc route