我在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);
}
你可能想看看這個問題:http://stackoverflow.com/questions/15167243/session-issue-when-having-async-session-start-method –
我試過了,但事實並非如此工作。 – user266909
它看起來像你使用異步的唯一原因是因爲你正在使用'HttpClient',可以使用['WebClient.DownloadString'](https://msdn.microsoft.com/en-us/library/fhd1f0sw(v = vs.110).aspx),而不是異步。 –