在Page_Load调用时,HttpClient.PostAsync会导致无限循环

时间:2017-10-10 09:51:07

标签: c# asp.net

我的代码后面有这个Web Api调用。这适用于使用我们AD的Windows凭证进行的单点登录。它所做的只是调用Web Api并检查用户是否已经过身份验证并且可以访问该应用程序。

我使用HttpClient.PostAsync成功调用了我的网络Api,但我想知道为什么它在Page_Load中多次调用了?

请参阅下面的Page_Load我如何调用Web Api:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            var languages = Language.Enabled().OrderByDescending(x => x.IsDefault);
            var selected = languages.Where(x => x.Code == HSESA.Library.Helpers.Context.PublicLanguage().Code).Select(x => x.Code).FirstOrDefault();

            Test();
        }
    }

以下是Test()方法以及我如何初始化HttpClient

 private static HttpClient client = new HttpClient();

 protected void Test()
    {

        string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
        string FromUrl = HttpContext.Current.Request.Url.AbsoluteUri;

        #region Old Code
        var postData = new List<KeyValuePair<string, string>>();
        postData.Add(new KeyValuePair<string, string>("Login", user));
        postData.Add(new KeyValuePair<string, string>("FromUrl", FromUrl));
        System.Net.Http.HttpContent content = new System.Net.Http.FormUrlEncodedContent(postData);

        string url = "http://localhost:1899";
        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        var response = client.PostAsync("/api/login/checkLogin", content).Result;

        if (response.IsSuccessStatusCode)
        {
            LoginItemViewModel data = null;
            string responseString = response.Content.ReadAsStringAsync().Result;
            Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(responseString);
            data = Newtonsoft.Json.JsonConvert.DeserializeObject<LoginItemViewModel>(responseString);
        }
        #endregion
    }

提前感谢能帮我解决问题的人。

0 个答案:

没有答案