2013-10-28 57 views
0

我连接到服务器使用基本身份验证,之后我打电话网页视图的URL与下面的代码后,再次显示Loginscreen -Window,但我已经登录。为什么会发生这种情况? 我该如何预防?的WebView通过基本身份验证的登录与HttpClient的

我的方式对服务器的身份验证:

private async void HttpClientCall(object sender, RoutedEventArgs e) 
{ 

    System.Diagnostics.Debug.WriteLine(this.GetType().Name + ": HTTPCLientCall entered"); 

    //System.Diagnostics.Debug.WriteLine("NetworkConnectivityLevel.InternetAccess: " + NetworkConnectivityLevel.InternetAccess); 

    //use this, for checking the network connectivity 
    System.Diagnostics.Debug.WriteLine("GetIsNetworkAvailable: " + System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()); 

    //var msg = new Windows.UI.Popups.MessageDialog("GetIsNetworkAvailable: " + System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()); 
    //msg.ShowAsync(); 


    HttpClient httpClient = new HttpClient(); 


    // Assign the authentication headers 
    httpClient.DefaultRequestHeaders.Authorization = CreateBasicHeader("username", "password"); 
    System.Diagnostics.Debug.WriteLine("httpClient.DefaultRequestHeaders.Authorization: " + httpClient.DefaultRequestHeaders.Authorization); 


    // Call out to the site 
    HttpResponseMessage response = await httpClient.GetAsync("https://URLHere"); 
    System.Diagnostics.Debug.WriteLine("response: " + response); 
    string responseAsString = await response.Content.ReadAsStringAsync(); 
    System.Diagnostics.Debug.WriteLine("response string:" + responseAsString); 

    //WebViewP.Source = new Uri("https://URLHere"); 
} 




public AuthenticationHeaderValue CreateBasicHeader(string username, string password) 
{ 
    byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(username + ":" + password); 

    String logindata = (username + ":" + password); 
    System.Diagnostics.Debug.WriteLine("AuthenticationHeaderValue: " + new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray))); 

    return new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); 
} 

那么我怎样才能解决?

+0

有可能是服务器设置一些身份验证Cookie做出的。使用fiddler并在服务器响应中查找set-cookies标头。如果是这样,那么你可以清除cookie容器,以防止被“登录”。 –

+0

我不想阻止被“登录”。我想保持登录状态。当httpClient完成授权后,我想导航/显示页面。如果服务器设置了一个cookie,我该怎么做?保存该cookie,然后再次调用该页面?还是有另一种方式来授权时调用webView? – brush51

回答

0

这是一个很长的一段时间,但你可以尝试在HttpClientHandler上设置凭据,并希望WebView将它取出。

var handler = new HttpClientHandler(); 
handler.Credentials = new NetworkCredential(username,password); 
HttpClient httpClient = new HttpClient(handler); 

问题是的WebView正在它自己的独立请求权,所以你与HttpClient的任何请求都独立于由的WebView

+0

对你来说很好,先生,我是C#新手,我对你的回答有几个问题,我当然希望你能花一分钟回答他们。首先,自UWP以来有两个HttpClient类,一个来自System命名空间,另一个来自Windows,你在代码片段中提到了哪一个?其次,在什么情况下WebView会选择HttpClient?据我可以告诉你只是初始化一个HttpClient而不提及代码中的WebView。 –