为什么这个网络api呼叫没有返回?

时间:2018-06-01 16:51:00

标签: c# .net asp.net-web-api async-await asp.net-web-api2

我的MVC应用程序的Global.asax中有以下方法:

protected void Application_OnPostAuthenticateRequest(object sender, EventArgs e)
{
    SetUserRolesToSession().GetAwaiter().GetResult();
}

protected async Task SetUserRolesToSession()
{
    var networkUserIdParts = networkUserId.Split(new char[] { '\\' });
    var baseUrl = ConfigurationManager.AppSettings["SecurityApiBaseUrl"].ToString();
    var userSearchRequest = new UserSearchRequest
    {
        NetworkUserId = Request.LogonUserIdentity.Name
    };
    var user = (await new SecurityApiServiceWrapper(baseUrl)
        .GetUsersAsync(userSearchRequest)).FirstOrDefault();

    Session["Roles" + "_" + networkUserId] = user?.Groups.Select(x => x.Name).ToList();
}

然后我在SecurityApiServiceWrapper中有以下代码:

public async Task<List<User>> GetUsersAsync(UserSearchRequest userSearchRequest)
{
    using (var client = GetHttpClient(_baseUrl))
    {
        var response = await client.PostAsJsonAsync("api/v1/users/search", userSearchRequest);
        if (response.IsSuccessStatusCode)
        {
            var users = await response.Content.ReadAsAsync<List<User>>();
            return users;
        }
        else //not 200
        {
        }
    }
}

public HttpClient GetHttpClient(string baseUrl)
{
    var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
    client.BaseAddress = new Uri(baseUrl);
    client.Timeout = Timeout.InfiniteTimeSpan;
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
    return client;
}

当代码进入等待client.PostAsJsonAsync时,进程卡住并且永远不会返回。我可以通过Postman进行相同的api调用,并且响应返回&lt; 1秒。知道问题可能是什么或如何调试?

0 个答案:

没有答案