如何在 Windows rt 上使用基本的 http 身份验证 - Visual Studio 2012 - C#

本文关键字:身份验证 http Visual 2012 Studio Windows rt | 更新日期: 2023-09-27 18:36:11

如何对 HTTPS URL Windows 8 应用商店应用程序使用基本 HTTP 身份验证。我正在使用Visual Studio 2012,C#和XAML。

当我使用 HTTPS URL 时,有什么需要注意的吗?

我尝试了以下方法:

#

1:###Code 已更新 - 最终运行解决方案

        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));
    }

我只想显示一个需要身份验证的HTTPS网站。我收到来自视觉工作室的警告,它停止工作:发送请求时出错。

"mscorlib 中发生了类型为'System.Net.Http.HttpRequestException'的第一次机会异常.dll"

如何在 Windows rt 上使用基本的 http 身份验证 - Visual Studio 2012 - C#

您可以使用更简单的方法来执行基本身份验证。

  • 首先创建一个 HttpClientHandler 实例。
  • 您可以根据需要设置 HttpClientHandler 实例的 Credentials 属性。
  • 使用接受 HttpMessageHandler 实例的构造函数初始化 HttpClient。