简体   繁体   English

如何中止称为Ajax方法的C#.net

[英]How to abort called ajax method c# .net

I have a ajax.cs class and I am calling methods from javascript side. 我有一个ajax.cs类,正在从javascript端调用方法。 So for this I registered it on default.aspx page load like this. 因此,为此,我在default.aspx页面加载中注册了它,如下所示。

Ajax.Utility.RegisterTypeForAjax(typeof(ajax));

Sometimes some methods taking a long time, At that time I want to abort this call. 有时某些方法花费很长时间,当时我想中止此调用。 How can I abort this request? 如何终止该请求?

I call method like this from js; 我从js调用这样的方法;

ajax.testMethod()

If you make your controller action return a Task, then you can have cancellation token as a parameter to the action. 如果使控制器动作返回任务,则可以将取消令牌作为动作的参数。 And this cancellation token is automatically triggered when the HTTP request is aborted. 当HTTP请求中止时,此取消令牌会自动触发。 And in the action, you can handle the token however you like to cancel the long-running operation. 并且在操作中,您可以处理令牌,但是您想取消长时间运行的操作。

Not sure if it works, but instead of aborting the ajax from the C# side, why don't you cancel it from the js side? 不知道它是否有效,而是为什么不从C#端取消ajax,而不是从js端取消它呢? in your ajax configuration, you can add a timeout parameter which, when happens, triggers the .error() function you can define, or leave it blank if you just want it to stop executing. 在ajax配置中,您可以添加一个超时参数,该参数在发生时会触发您可以定义的.error()函数,或者如果您只是希望它停止执行,则将其留空。

For js: 对于js:

var ajax = new XMLHttpRequest();
ajax.post('your url');
ajax.timeout(10000); //or any time in milliseconds to set a timeout.
ajax.ontimeout= function(){ }//optional, just if you want a callback when ajax times out

For jQuery: 对于jQuery:

$.ajax({
   url:'yoururl',
   timeout: 10000,
   error: function(){
   }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM