我有一个由 jquery ajax 请求调用的异步操作:
看法:
$.ajax({
url: "@Url.Action("StartVerification", "Devices")",
global: false,
data: JSON.stringify(machineIds),
contentType: 'application/json',
type: 'POST'
...
控制器:
[HttpPost]
[SessionExpireFilter(Order = 1)]
[CheckPermissions(Order = 2)]
[AjaxMessagesFilter(Order = 3)]
[AsyncTimeout(30000, Order = 4)]
[HandleError(ExceptionType = typeof(TimeoutException), View = "TimeoutError", Order = 5)]
public async Task<JsonResult> StartVerification(ICollection<Machine> machines)
{
Dictionary<int, bool> collection = new Dictionary<int, bool>();
foreach (var machine in machines)
{
Response response = new Response();
try
{
response = await this.deviceRepository.StartVerification(machine);
}
catch (Exception ex)
{
response.Success = false;
}
collection.Add(machine.MachineID, response.Success);
}
return this.Json(collection.ToDictionary(x => x.Key.ToString(), y => y.Value));
}
网络服务调用:
public async Task<Response> StartVerification(Machine machine, CancellationToken cancelToken = default(CancellationToken))
{
WebService WebServiceForTask = WebServiceFactory.NewInstance;
return await Task.Run(() => WebServiceForTask.StartVerificationForWebSite(machine.SiteID, machine.MachineID));
}
我遇到的问题是,当执行 StartVerification 操作时调用然后查询 Web 服务。对该结果的查询最多可能需要几秒钟,在此期间用户可能会按下浏览器的刷新按钮。处理这种情况并简单地中止呼叫等的最佳方法是什么?
编辑:也许我问错了问题。这里的问题是,当我 StartVerification 并点击刷新页面 F5 时,页面不会刷新,直到我收到来自 webservice 的响应......并且看起来 Action 没有异步运行。我希望它能够工作,以便如果已经调用了控制器操作并等待来自 web 服务的响应,我仍然应该能够简单地浏览离开我正在调用该操作的页面。