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 the client side but not on the server side.
Updated:
I used async action instead of sync action, but I didn't get what I want! As you know server can't process more than one request at the same time that's causes each request have to wait till the previous one is finished even if previous request is canceled by $.Ajax.Abort() method. I know if I use [SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)] attribute it almost what I want but it doesn’t satisfy me.
Above all I want to abort processing method on server side by user. That's it :)
You may want to look at using the following type of controller Using an Asynchronous Controller in ASP.NET MVC
and also see if this article helps you out as well Cancel async web service calls, sorry I couldn't give any code examples this time.
I've created an example as a proof of concept to show that you can cancel server side requests. My github async cancel example
If you're calling other sites through your code you have two options, depending on your target framework and which method you want to use. I'm including the references here for your review:
WebRequest.BeginGetResponse for use in .Net 4.0 HttpClient for use in .Net 4.5, this class has a method to cancel all pending requests.
Hope this gives you enough information to reach your goal.
Here is an example Backend:
[HttpGet]
public List<SomeEntity> Get(){
var gotResult = false;
var result = new List<SomeEntity>();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With