我在Global.asax.cs中的session_start中重构我的ASP MVC代码,并对外部服务进行异步调用。我要么在IE中获得一个无限旋转的白页,要么执行立即返回到调用线程。在Session_start()中,当我尝试.Result时,我得到了带有旋转IE图标的白页。当我尝试.ContinueWith()时,执行返回到下一行,这取决于异步的结果。因此,authResult始终为null。有人可以帮忙吗?感谢。
这是来自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 :(得分:0)
It doesn't make sense to call User_Controller from Session_Start.
You want to call VhaHelpersLib directly inside Session_Start, if VhaHelpersLib doesn't have any dependencies.
Since Session_Start is not async, you want to use Result.
var setting = ConfigurationManager.AppSettings["userWebApiEndpoint"];
UserProfile profile = await VhaHelpersLib.WebApiBroker.Get<UserProfile>(
setting, "User/Profile/" + networkName).Result;
if (profile == enumAuthenticationResult.Authorized) {
...
}