使用Async c#servicehandler的Ajax请求

时间:2016-06-10 10:26:28

标签: c# ajax asynchronous

我执行jquery ajax请求。目的地是一个ashx处理程序。 问题是在后端调用第二个异步请求。由于这个事实,我将陷入错误" jquery ajax请求的情况(错误:"异步模块或处理程序在异步操作仍在等待时完成")。

这里是代码:

Ajax电话:

      $.ajax({
                type: "POST",
                cache: false,
                url: 'ajax/HandlerAsync.ashx',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: '{method: "'+ data.value +'" , meeting: '+ meeting +' }',
                success: function (data, status, xhr) {

                },
                error: function (xhr, status, error) {

                }
            });

后端:

 public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
    {
        httpContext = context;

        string json = new StreamReader(context.Request.InputStream).ReadToEnd();
        dynamic test = JsonConvert.DeserializeObject(json);
        AjaxRequest ajax = JsonConvert.DeserializeObject<AjaxRequest>(json);

        Async async = new Async(cb, extraData);
        // store a little context for us to use later as well
        async.context = context;

        if (String.IsNullOrEmpty(ajax.meeting.EventId))
        {
            var calendarEntryId = sendCalendarInvitations((ajax.meeting));
        }
        else
        {
            updateCalendarInvitations(ajax.meeting);
        }
        async.SetCompleted();

        return async;
    }


  public void EndProcessRequest(IAsyncResult result)
    {
        // Finish things
        Async async = result as Async;
        async.context.Response.Write("<H1>This is an <i>Asynchronous</i> response!!</H1>");
    }

问题出现在以下方法中,该方法将在var dcr = await discClient.DiscoverCapabilityAsync(capability)上的send / updatecalendarinvitation中调用; 通过执行此操作,&#34; EndProcessRequest&#34;很快就会被召唤。我只是希望它被调用,当日历实现时......

 AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", WebConfigurationManager.AppSettings["AuthorizationUri"], SettingsHelper.TenantId));
            DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                    async () =>
                    {

                        var authResult = await authContext.AcquireTokenByRefreshTokenAsync(this.refreshToken,
                        new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey),
                        SettingsHelper.DiscoveryServiceResourceId);
                        return authResult.AccessToken;
                    });

            var dcr = await discClient.DiscoverCapabilityAsync(capability);

            OutlookServicesClient exClient = new OutlookServicesClient(dcr.ServiceEndpointUri,
           async () =>
           {
               var authResult = await authContext.AcquireTokenByRefreshTokenAsync(this.refreshToken,
                   new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey),
                   dcr.ServiceResourceId);
               return authResult.AccessToken;
           });
            return exClient;

后端代码工作正常,方法都将被调用。但我只是想得到正确的反馈。 我期待你的反馈意见。 谢谢!

1 个答案:

答案 0 :(得分:2)

好的解决了。 我将上下文(上面的最后一个代码部分)包装在一个单独的Task中,它不会触发“EndprocessRequest”。

 var client = System.Threading.Tasks.Task.Run<OutlookServicesClient>(() => {
            return o365Api.CreateOutlookClientAsync("Calendar");
        });