天天看点

Struggling trying to get cookie out of response with HttpClient in .net 4.5

      public static async Task<LoginModel> Login(string UserName,string Password)
		{
			var model = new LoginModel ();
			try 
			{
				var url = string.Format("{0}&requestType={1}&requestAction={2}&Email={3}&Password={4}", Server_API_Base, "Users","ValidateUser",Uri.EscapeDataString(UserName), Uri.EscapeDataString(Password));


				var cookieContainer = new CookieContainer();
				using(var handler=new HttpClientHandler()
				{
					CookieContainer= cookieContainer,
					UseCookies=true,
					UseDefaultCredentials=false
				})
				using (var client = new HttpClient (handler){ BaseAddress=new Uri(url)}) 
				{
					var result = await client.GetStringAsync (url);
                    responseCookies = cookieContainer.GetCookies(new Uri(url)).Cast<Cookie>(); //get coolises


                     model = JsonConvert.DeserializeObject<LoginModel>(result);
					if (model.Success) 
					{
						App.Username=model.Data.FirstName+ "  "+model.Data.LastName;
						App.UserID=model.Data.UserID;
					} 
					return model;
				}
			} 
			catch (Exception ex) 
			{
				model.GeneralError="Network Error";
				return model;
			}
		}


        public static async Task<DashboardCellModel> SyncRotes()
        {
            try
            {
                var url = string.Format("{0}&requestType={1}&requestAction={2}&UserID={3}", Server_API_Base, "MobileUpdate", "GetUpdateSyncSetForTablets", "169");
                var cookieContainer = new CookieContainer();
                using (var handler = new HttpClientHandler()
                {
                    CookieContainer = cookieContainer
                })
                using (var client = new HttpClient(handler) { BaseAddress = new Uri(url) })
                {
                    foreach (var cookie in responseCookies)
                    {      
// send a cookie
                        cookieContainer.Add(new Uri(url), cookie);
                    }


                    var result = await client.GetStringAsync(url);


                }
                return null;
            }
            catch (Exception)
            {
                return null;
            }
		
        }