How can I abort an action in ASP.NET MVC

后端 未结 4 1873
野趣味
野趣味 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 23:02

    Here is an example Backend:

    [HttpGet]
    public List Get(){
            var gotResult = false;
            var result = new List();
            var tokenSource2 = new CancellationTokenSource();
            CancellationToken ct = tokenSource2.Token;
            Task.Factory.StartNew(() =>
            {
                // Do something with cancelation token to break current operation
                result = SomeWhere.GetSomethingReallySlow();
                gotResult = true;
            }, ct);
            while (!gotResult)
            {
                // When you call abort Response.IsClientConnected will = false
                if (!Response.IsClientConnected)
                {
                    tokenSource2.Cancel();
                    return result;
                }
                Thread.Sleep(100);
            }
            return result;
    }
    

    Javascript:

    var promise = $.post("/Somewhere")
    setTimeout(function(){promise.abort()}, 1000)
    

    Hope I'm not to late.

提交回复
热议问题