2015-06-24 37 views
0

我正在从同步方法调用C#ASP.Net Web应用程序中的异步Web API。我得到错误。 发生一个或多个错误。发送请求时发生错误。 底层连接已关闭:接收时发生意外错误。 无法从传输连接读取数据:现有连接被远程主机强制关闭。在同步方法中调用异步web api方法throws error

如果我使用异步方法从Windows窗体应用程序调用相同的异步Web API,则Web API会返回完美值。我必须在Web应用程序中使用同步方法,因此在Windows应用程序中成功测试的代码不能用于Web应用程序。 以下是部分代码。

private string SECURE_API_Async(string WebApiURL, HttpContent httpContent, string[] apiNames, HTTP httpMethod, DictionaryEntry[] apiValues) 
    { 
     try 
     { 
      using (httpContent) 
      { 

       Last_HTTPRequestContent = httpContent == null ? "null" : httpContent.ReadAsStringAsync().Result; 
       HttpClient httpClient = new HttpClient(httpClientHandler); 
       httpClient.BaseAddress = new Uri(WebApiURL); 

       if (SessionTokenID != null) 
       { 
        httpClient.DefaultRequestHeaders.Add("SessionTokenID", SessionTokenID); 
       } 

       httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml")); 
       string target_URI = "api"; 

       foreach (string apiName in apiNames) 
       { 
        target_URI = string.Format("{0}/{1}", 
         target_URI, 
         apiName); 
       } 

       string target_URI_parameters = string.Empty; 

       if (apiValues != null) 
       { 
        target_URI_parameters = CreateParameterString(apiValues); 
       } 
       target_URI = (target_URI_parameters == string.Empty) ? target_URI : string.Format("{0}?{1}", target_URI, target_URI_parameters); 

       _lastURL = httpClient.BaseAddress.ToString() + target_URI; 
       Last_HTTPstatus = 0; 
       Last_ReasonPhrase = string.Empty; 
       Last_HTTPResponse = null; 
       Last_HTTPResponseString = string.Empty; 

       HttpResponseMessage response = null; 

       try 
       { 
        switch (httpMethod) 
        { 
         case HTTP.PUT: 
          { 
           response = httpClient.PutAsync(target_URI, httpContent).Result; 
           break; 
          } 

当PutAsync方法被调用时出现错误。现在

如果我改变了方法

private **async** **Task<string>** SECURE_API_Async(string WebApiURL,  HttpContent httpContent, string[] apiNames, HTTP httpMethod, DictionaryEntry[] apiValues) 

和API调用

response = **await** httpClient.PutAsync(target_URI, httpContent); 

我得到正确的响应。 我搜索网后了解到既是

response = **await** httpClient.PutAsync(target_URI, httpContent); 

(当调用方法有异步关键字的含义调用方法是aynchronous)和

response = httpClient.PutAsync(target_URI, httpContent).**Result**; 

(当该方法不具有异步的关键字意义呼叫方式同步)

应该返回正确的响应消息。 但我的同步方法抛出基础连接错误。 有人可以帮忙吗? 谢谢。

回答

0

我传递了错误的证书。所以我得到错误现有的连接被远程主机强行关闭。奇怪的错误。如果您使用MS技术工作,那将是头痛之一。他们只是不会抛出适当的错误。正确的错误应该是用户证书是错误的。

但是,如果您使用结果 的例如,您可以调用异步方法。

HttpResponseMessage响应= httpClient.PutAsync(target_URI,httpContent)。结果;从同步方法//同步调用

AND

HttpResponseMessage响应=等待httpClient.PutAsync(target_URI,httpContent); //同步从具有async关键字前缀的异步方法调用

给出了相同的结果。