简体   繁体   English

取消http.get请求并还原数据

[英]Cancel http.get request and revert data

I have a page where we upload a .csv file to the database. 我有一个页面,我们在其中上传一个.csv文件到数据库。 we call a web api method that reads the file and insert the data into a table. 我们调用一个Web api方法,该方法读取文件并将数据插入表中。 When we upload the file a popup appears with a cancel button. 当我们上传文件时,会出现一个带有取消按钮的弹出窗口。 What I am trying to do is to cancel the file upload process if user press the cancel button. 我要执行的操作是,如果用户按“取消”按钮,则取消文件上传过程。 For doing that I have created a promise and calling it on click of cancel button and it is cancelling the http request but the problem that I am facing is the data that is already imported into the database stays there. 为此,我创建了一个诺言,然后单击“取消”按钮将其调用,这将取消http请求,但是我面临的问题是已经导入数据库的数据仍然存在。 For instance if we have 100 rows in the file and by the time I press cancel button 50 rows were already inserted to the database those rows stays there. 例如,如果文件中有100行,并且在我按“取消”按钮时,已经有50行插入到数据库中,那么这些行将保留在那里。 I need some help in figuring out how to revert the data that is already inserted in the table. 我需要一些帮助来弄清楚如何还原表中已插入的数据。 Here is the code that I am working with: 这是我正在使用的代码:

var requestPromise = $http({
  method: 'POST',
  url: mpCONFIG.apiServiceBaseUri + 'import/fileImport',
  data: formData,
  transformRequest: angular.identity,
  timeout: canceller.promise,
  headers: {
    'Content-Type': undefined
  }
});
return requestPromise.success(function(resp, status) {
    file.progress = undefined;
    if (typeof resp != 'undefined' && resp != null && resp.length > 0) {

      $rootScope.caseFileId = resp[0];
      listImportRows(1, resp[0]);
    }
  })
  .error(function(data, status) {
    $scope.waitOnLoadingFile(false);
    file.progress = undefined;
  });
};

$rootScope.cancelLoadingFile = function() {
  canceller.resolve("User Cancelled");
  $scope.waitOnLoadingFile(false);
  $window.location.reload();
}

Edit: What I found out that it is not cancelling the request at all. 编辑:我发现它根本不取消请求。 The initial impression of stopping at half way was not correct and was due to some other issue. 中途停止的最初印象是不正确的,并且是由于其他一些问题。 So when I press the cancel button cancelLoadinfFile is called but seems like canceller.resolve is not cancelling the request. 因此,当我按下取消按钮时,调用了cancelLoadinfFile,但似乎canceller.resolve并未取消请求。 Below is the web api method. 以下是Web api方法。

  [Route("fileImport")]
    [HttpPost]
    public System.Threading.Tasks.Task<IHttpActionResult> UploadImage()
    {
        try
        {
            IEnumerable<Models.mlsp.Firm> firms = (from cs in User.Firms(db)
                                                   select cs);

            HttpRequestMessage request = this.Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(Properties.Settings.Default.UploadTempFolder);

            string user = RequestContext.Principal.Identity.Name;

            System.Threading.Tasks.Task<IHttpActionResult> task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith<IHttpActionResult>(o =>
                {
                    System.Net.HttpStatusCode resultStatus = HttpStatusCode.OK;
                    int?[] result = new int?[provider.FileData.Count];

                    try
                    {
                        for (int i = 0; i < provider.FileData.Count; i++)
                        {
                            result[i] = Logic.mlsp.Case.LoadFromFile(User, db, provider.FileData[i].LocalFileName, firms);
                        }
                        return ResponseMessage(new HttpResponseMessage()
                        {
                            StatusCode = resultStatus,
                            Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(result))
                        });
                    }
                    catch (Exception ex)
                    {
                        Helpers.LogHelper.LogError(ex);
                        throw;
                    }
                }
            );
            return task;
        }
        catch (Exception ex)
        {
            Helpers.LogHelper.LogError(ex);
            throw;
        }
    }

According to this link, http://www.davepaquette.com/archive/2015/07/19/cancelling-long-running-queries-in-asp-net-mvc-and-web-api.aspx , you can add a CancellationToken parameter to the controller method. 根据此链接http://www.davepaquette.com/archive/2015/07/19/cancelling-long-running-queries-in-asp-net-mvc-and-web-api.aspx ,您可以添加控制器方法的CancellationToken参数。 When the client cancels the request the token will be canceled as well. 当客户端取消请求时,令牌也将被取消。 You need to pass this token along to the task or monitor the IsCancellationRequested property as necessary. 您需要将此令牌传递给任务,或根据需要监视IsCancellationRequested属性。

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

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