2015-08-31 28 views
0

我需要在Global.asax.csSession_Start事件中獲取用戶配置文件。在session_start中調用webapi

用戶配置文件數據通過HttpClient從WebAPI端點檢索。

當單步調試代碼,響應是:

狀態= WaitingForActivation

我不知道如何「激活」異步響應和數據反序列化到我的模型類。這是我的代碼在普通的MVC控制器中工作,但是這個需要在Session_Start中執行。感謝您的幫助。

protected void Session_Start(object sender, EventArgs e) 
{ 
    string id = Session.SessionID; 
    string[] DomainUserName = HttpContext.Current.User.Identity.Name.Split(new char[] { '\\' }); 

    string svcLocation = System.Configuration.ConfigurationManager.AppSettings["thisWebApiEndpoint"]; 
    string svcParameter= "User/12345"; 
    WebHelper.WebApiBorker.WebApiEndpoint = svcLocation; 
    var httpClient = WebHelper.WebApiBorker.GetClient(); 
    myMVC.Models.WebApiUserModel UserVM = new myMVC.Models.WebApiUserModel(); 

    //make webapi call to webapi/user 
    var response = httpClient.GetAsync(svcParameter); //<---what to do after this line 
    //if(response.IsSuccessStatusCode) 
    //{ 
    // string content = await response.Content.ReadAsStringAsync(); 
    // UserVM = JsonConvert.DeserializeObject<myMVC.Models.WebApiUserModel>(content); 
    //} 

回答

2

問題是您正在從非異步方法調用異步方法。

把你的WebAPI調用到它自己的,異步函數:

private async Task<myMVC.Models.WebApiUserModel> GetUserVMAsync(string svcParameter) 
{ 
    var httpClient = WebHelper.WebApiBorker.GetClient(); 
    myMVC.Models.WebApiUserModel UserVM = new myMVC.Models.WebApiUserModel(); 

    //make webapi call to webapi/user 
    var response = await httpClient.GetAsync(svcParameter); 
    if(response.IsSuccessStatusCode) 
    { 
     string content = await response.Content.ReadAsStringAsync(); 
     UserVM = JsonConvert.DeserializeObject<myMVC.Models.WebApiUserModel>(content); 
    } 

    return UserVM; 
} 

然後,使用一個ContinueWithSession_Start調用函數:

GetUserVMAsync(svcParameter).ContinueWith(result => { 
    //Do something with the UserVM that was returned 
}; 

或者同步調用它:

var vm = GetUserVMAsync(svcParameter).Result; 
+0

謝謝。我添加了代碼 GetUserVMAsync(svcParameter).ContinueWith(result => {0} {0} {0} {0} myUserVM = result.Result; Session [「userProfile」] = myUserVM; }; – user266909