How do I prevent multiple form submission in .NET MVC without using Javascript?

后端 未结 13 2136
情深已故
情深已故 2020-11-28 02:36

I want to prevent users submitting forms multiple times in .NET MVC. I\'ve tried several methods using Javascript but have had difficulties getting it to work in all browser

13条回答
  •  温柔的废话
    2020-11-28 03:05

    You can do this by creating some sort of static entry flag that is user specific, or specific to whatever way you want to protect the resource. I use a ConcurrentDictionary to track entrance. The key is basically the name of the resource I'm protecting combined with the User ID. The trick is figuring out how to block the request when you know it's currently processing.

    public async Task SlowAction()
    {
        if(!CanEnterResource(nameof(SlowAction)) return new HttpStatusCodeResult(204);
        try
        {
            // Do slow process
            return new SlowProcessActionResult();
        }
        finally
        {
           ExitedResource(nameof(SlowAction));
        }
    }
    

    Returning a 204 is a response to the double-click request that will do nothing on the browser side. When the slow process is done, the browser will receive the correct response for the original request and act accordingly.

提交回复
热议问题