使用服务访问控制台应用程序中的服务需要证书

时间:2014-06-19 10:51:14

标签: c# ssl

我正在尝试从下面的服务请求url中读取数据。当我在浏览器中打开它时,我可以看到数据。但是当我想使用ConsoleApplication做同样的事情时它不起作用。

https://wb01.miracast.com/Primary/services/requestlist/getrequestlist?id=80FC46F4&queryby=requestid&format=xml

我注意到的一件事是它要求我选择证书,当我选择证书时(在这种情况下,它是sr.dns.miracast.com(IT Machine Auth CA 2)),它返回数据并显示它在浏览器中。我在我的桌面上的Personal,TrustedRootAuthority中安装了此证书,我的代码也在Visual Studio中运行。

现在如何使用c#console应用程序代码实现相同目的。我的意思是如何为代码指定证书?

我尝试了以下但是它会在reposne catch块中抛出Not found错误。

   private void Button_Click(object sender, RoutedEventArgs e)
    {

        // retrieve an avatar image from the Web
        string avatarUri = "https://wb01.miracast.com/Primary/services/requestlist/getrequestlist?id=80FC46F4&queryby=requestid&format=xml";
        HttpWebRequest request =
            (HttpWebRequest)HttpWebRequest.Create(avatarUri);
        request.BeginGetResponse(GetAvatarImageCallback, request);
    }

    private void GetAvatarImageCallback(IAsyncResult result)
    {

        HttpWebRequest request = result.AsyncState as HttpWebRequest;
        if (request != null)
        {
            try
            {
                WebResponse response = request.EndGetResponse(result);
                //avatarImg = Texture2D.FromStream(
                //    graphics.GraphicsDevice,
                //    response.GetResponseStream());
            }
            catch (WebException e)
            {
               // gamerTag = "Gamertag not found.";
                return;
            }
        }

    }

1 个答案:

答案 0 :(得分:0)

通过代码附加相同的证书后,它就可以了。

        string avatarUri = "https://wb01.miracast.com/Primary/services/requestlist/getrequestlist?id=80FC46F4&queryby=requestid&format=xml";
        HttpWebRequest request =
            (HttpWebRequest)HttpWebRequest.Create(avatarUri);

        request.Method = "GET";        // Post method


        X509Certificate cert = X509Certificate.CreateFromCertFile(@"C:\Users\kim\Desktop\oas-test.cer");
        request.ClientCertificates.Add(cert);
        // Attaching the Certificate To the request

        System.Net.ServicePointManager.CertificatePolicy =
                               new TrustAllCertificatePolicy();

        request.UseDefaultCredentials = true;
        request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
        HttpWebResponse wResp = (HttpWebResponse)request.GetResponse();

        Encoding enc = System.Text.Encoding.GetEncoding(1252);
        StreamReader loResponseStream = new
          StreamReader(wResp.GetResponseStream(), enc);

        string Response = loResponseStream.ReadToEnd();

        loResponseStream.Close();
        wResp.Close();