在monodevelop上遇到麻烦

时间:2012-09-21 08:52:21

标签: c# mono httpwebrequest monodevelop

我刚刚从ubuntu软件中心安装了monodevelop并创建了一个解决方案。我正在尝试做WebRequest.create(url)。但它不断抛出“认证或解密失败”。我究竟做错了什么?如果我没有做错什么我应该怎么做才能完成上述工作!

我已经搜索了这个,但我无法找到解决方案来解决我的问题!

这是我做的......

public static string AccessURL(string url, string postcontent)
    {
        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        byte[] byteArray = Encoding.UTF8.GetBytes(postcontent);
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = byteArray.Length;
        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();
        WebResponse response = request.GetResponse();
        dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        reader.Close();
        dataStream.Close();
        response.Close();
        return responseFromServer;
    }

提前致谢!

1 个答案:

答案 0 :(得分:4)

该错误表明您正在尝试访问SSL / TLS加密资源。 Mono默认不信任任何这些网站,并由开发人员决定是否要访问该资源。有关详情,请参阅mono's security FAQ

所以一种方法是在你的类中实现ServerCertificateValidationCallback:

using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

public class MyAwesomeProgram
{
    public MyAwesomeProgram() 
    {
        ServicePointManager.ServerCertificateValidationCallback =
                ValidateServerCertficate;
    }

    private static bool ValidateServerCertficate(object sender, X509Certificate certificate,
        X509Chain chain, SslPolicyErrors sslpolicyerrors)
    {
        //This is where you should validate the remote certificate
        return true;
    }

    public void FetchAwesomeStuff (string url) 
    {
        var wr = WebRequest.Create (url);
        var stream = wr.GetResponse().GetResponseStream ();
        Console.WriteLine (new StreamReader (stream).ReadToEnd ());
    }
}

mono documentation about using Certificate Policies and Trusting Roots中有更多示例。 通知上面的示例忽略了安全性并接受了所有证书,即使是那些您可能不信任的证书。建议不要使用!