Reputation: 1863
I need to get user profile in the Session_Start
event in Global.asax.cs
.
The user profile data is retrieved via HttpClient
from a WebAPI endpoint.
When stepping through the code, the response is:
Status = WaitingForActivation
I don't know how to "Activate" the async response and deserialize the data into my model class. Here is my code that works in normal MVC controller, but this one needs to be executed in the Session_Start
. Thank you for your help.
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);
//}
Upvotes: 0
Views: 878
Reputation: 11914
The issue is that you're calling an async method from a non-async method.
Put your WebAPI call into it's own, async function:
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;
}
Then either use a ContinueWith to call the function from Session_Start
:
GetUserVMAsync(svcParameter).ContinueWith(result => {
//Do something with the UserVM that was returned
};
Or call it synchronously:
var vm = GetUserVMAsync(svcParameter).Result;
Upvotes: 2