从异步请求获取Http响应标头

时间:2019-04-30 15:59:00

标签: async-await httpresponsemessage

我需要了解如何从异步Web服务请求中获取HttpResponseMessageProperty。

我正在尝试将C#控制台应用程序迁移到Azure Function应用程序,并且连接的服务中现在可用的唯一方法是异步的。

我得到的错误是:

System.Private.ServiceModel: This OperationContextScope is being disposed out of order.

据我所知,该错误很可能是由于OperationContextScope在另一个线程上运行而OperatonContextScope是特定于线程的。

MS docs网站上有以下建议:

  

如果您需要调用“ await”进行异步调用,请在   OperationContextScope块。

虽然不确定我如何实现这一目标,所以在这里是我的问题。

这是我的代码:

BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport)
        {

            AllowCookies = true,
            SendTimeout = new TimeSpan(0, httpTimeout, 0),
            ReceiveTimeout = new TimeSpan(0, httpTimeout, 0),
            MaxBufferSize = int.MaxValue,
            MaxReceivedMessageSize = int.MaxValue

        };

        /* set the https endpoint and create the service client object */
        EndpointAddress serviceEndpoint = new EndpointAddress(serviceBaseUrl + serviceName);
        AuthenticationServicePortTypeClient service = new AuthenticationServicePortTypeClient(binding, serviceEndpoint);

        /* set the request attributes and login */
        Login loginRequest = new Login()
        {

            UserName = authUser,
            Password = authPass,
            DatabaseInstanceId = databaseInstance,
            DatabaseInstanceIdSpecified = true

        };

        using (new OperationContextScope(service.InnerChannel))
        {

            LoginResponse1 loginResponse = await service.LoginAsync(loginRequest);


            if (loginResponse.LoginResponse.Return)
            {

                HttpResponseMessageProperty response = (HttpResponseMessageProperty)OperationContext.Current.IncomingMessageProperties[HttpResponseMessageProperty.Name];
                sessionCookie = response.Headers["Set-Cookie"];

            }

        }

在HttpResponseMessageProperty行上引发了异常。

我只需要能够从标题中获取cookie。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我没有看到完整的方法和调用代码,只是推测您没有等待该代码,并且在执行引发异常的行时已经处置了某些东西。