How can I abort an action in ASP.NET MVC

后端 未结 4 1839
野趣味
野趣味 2020-12-31 22:31

I want to stop the actions that are called by the jQuery.ajax method on the server side. I can stop the Ajax request using $.ajax.abort() method on

4条回答
  •  隐瞒了意图╮
    2020-12-31 22:46

    A simple solution is to use something like below. I use it for cancelling long running tasks (specifically generating thousands of notifications). I also use the same approach to poll progress and update progress bar via AJAX. Also, this works practically on any version of MVC and does not depends on new features of .NET

    public class MyController : Controller
    {
    
    private static m_CancelAction = false;
    
    public string CancelAction()
    {
        m_CancelAction = true;
        return "ok";
    }
    
    public string LongRunningAction()
    {
        while(...)
        {
            Dosomething (i.e. Send email, notification, write to file, etc)
    
            if(m_CancelAction)
            {
                m_CancelAction = false;
                break;
                return "aborted";
            }
        }
    
        return "ok";
    }
    }
    

提交回复
热议问题