2016-07-11 37 views
1

我在Global.asax.cs中的session_start中使用异步调用外部服务来重构我的ASP MVC代码。我要么在IE中获得无限旋转的白页,要么立即执行返回到调用线程。在Session_start()中,当我尝试.Result时,我得到了带有旋转IE图标的白页。当我尝试.ContinueWith()时,执行返回到依赖于异步结果的下一行。因此,authResult始终为空。有人可以帮忙吗?谢谢。async getting no

这是从在session_start()

  if (Session["userProfile"] == null) { 
      //call into an async method 
      //authResult = uc.checkUserViaWebApi(networkLogin[userLoginIdx]).Result; 
      var userProfileTask = uc.checkUserViaWebApi(networkLogin[userLoginIdx]) 
      .ContinueWith(result => { 
       if (result.IsCompleted) { 
       authResult = result.Result; 
       } 
      }); 

      Task.WhenAll(userProfileTask); 

      if (authResult.Result == enumAuthenticationResult.Authorized) { 

这是User_Controller类

public async Task <AuthResult> checkUserViaWebApi(string networkName) { 
     UserProfile _thisProfile = await VhaHelpersLib.WebApiBroker.Get <UserProfile> (
     System.Configuration.ConfigurationManager.AppSettings["userWebApiEndpoint"], "User/Profile/" + networkName); 


     AuthResult authenticationResult = new AuthResult(); 

     if (_thisProfile == null) /*no user profile*/ { 
     authenticationResult.Result = enumAuthenticationResult.NoLSV; 
     authenticationResult.Controller = "AccessRequest"; 
     authenticationResult.Action = "LSVInstruction"; 
     } 

这是助手的类,它使用的HttpClient

实际调用
public static async Task<T> Get<T>(string baseUrl, string urlSegment) 
    { 
     string content = string.Empty; 
     using(HttpClient client = GetClient(baseUrl)) 
     { 

     HttpResponseMessage response = await client.GetAsync(urlSegment.TrimStart('/')).ConfigureAwait(false); 
     if(response.IsSuccessStatusCode) 
     { 
      content = await response.Content.ReadAsStringAsync(); 

     } 
     return JsonConvert.DeserializeObject<T>(content); 
     } 
+0

你可能想看看这个问题:http://stackoverflow.com/questions/15167243/session-issue-when-having-async-session-start-method –

+0

我试过了,但事实并非如此工作。 – user266909

+0

它看起来像你使用异步的唯一原因是因为你正在使用'HttpClient',可以使用['WebClient.DownloadString'](https://msdn.microsoft.com/en-us/library/fhd1f0sw(v = vs.110).aspx),而不是异步。 –

回答

0

Session_Start调用User_Controller没有任何意义。

如果VhaHelpersLib没有任何依赖关系,您想直接在Session_Start内呼叫VhaHelpersLib。

由于Session_Start不是异步的,所以想要使用结果

var setting = ConfigurationManager.AppSettings["userWebApiEndpoint"]; 
UserProfile profile = await VhaHelpersLib.WebApiBroker.Get<UserProfile>(
     setting, "User/Profile/" + networkName).Result; 

if (profile == enumAuthenticationResult.Authorized) { 
    ... 
} 
+0

user_controller具有确定授权级别的业务逻辑。代码片段只显示了一小部分逻辑。这不是session_start()问题。此外,您所建议的等待将不会编译,因为这需要将session_start()的签名更改为异步。 – user266909

+0

你最后使用了**结果**吗?基本上,结果会阻止,直到任务完成。例如,在你原来的问题中,'var userProfileTask = uc.checkUserViaWebApi(networkLogin [userLoginIdx])。Result;' – Win

+0

谢谢。它工作,我离开了user_controller类中的沉重的业务逻辑。 – user266909

相关问题