如何将curl命令移植到RestSharp?如何排除故障?

时间:2014-10-30 22:22:08

标签: c# mono restsharp

我有一些工作curl命令到Web服务,现在我想将它们移动到C#程序。我正在使用RestSharp,并尝试使用最简单的Web服务调用,但只是不断收到一般错误消息,我有点难过如何解决它。

有没有办法查看正在发送的标头和确切的网址,以及正在接收的标头?

卷曲的例子基本上是这样的:

curl --user user:pw https://example.com/api/version

我的C#代码是:

var client = new RestClient("https://example.com");
client.Authenticator = new HttpBasicAuthenticator("user", "pw");
var request = new RestRequest ("api/version");
var response = client.Execute(request);
Console.WriteLine (response.Content);   
Console.WriteLine (response.StatusCode);    
Console.WriteLine (response.ErrorMessage);  

这给了我:

RestSharp.RestRequest

0
Error getting response stream (Write: The authentication or decryption has failed.): SendFailure

我在Linux上使用Mono。这会有关系吗?但我可以在StackOverflow上找到一些(更高级)单声道标签的问题,所以它应该可行。 (?)

如果用户名/密码确实存在问题,我会得到403状态,而不是零状态,我认为?

P.S。如果重要,我的其余部分是:

using System;
using System.Net;
using RestSharp;

namespace webtest
{
    class MainClass
    {
        public static void Main (string[] args)
        {
        ...(above code)
        }
    }
}

1 个答案:

答案 0 :(得分:0)

关于故障排除

到目前为止,我可以建议:

这足以让我看到http网址有效,https网址失败。

(如果您需要更多故障排除,并且正在使用https,则下面显示的sender参数包含有关发送到远程服务器的请求的各种字段。)

关于移植卷曲命令

默认情况下,linux上的curl使用它在/etc/ssl/certs中找到的证书。 Mono的毯子等价物是mozroots --import --ask-remove,它将导入所有证书(见Mono security FAQ)。

另一种方法是将它放在程序的最顶端:

ServicePointManager.ServerCertificateValidationCallback +=
    (sender, certificate, chain, sslPolicyErrors) => {
    //Console.WriteLine(certificate.ToString());
    return true;
    };

注释行可用于向用户报告证书,以交互方式获得批准,或检查证书指纹与预期的证书指纹。只需返回true即表示所有证书都是可信任且未经检查的。

奖励:证书检查

以下是检查特定证书的一种方法:

ServicePointManager.ServerCertificateValidationCallback +=
    (sender,certificate,chain,sslPolicyErrors) => {
    if(((System.Net.HttpWebRequest)sender).Host.EndsWith("google.com") ){
        if(certificate.GetCertHashString() == "83BD2426329B0B69892D227B27FD7FBFB08E3B5E"){
            return true;
        }
        Console.WriteLine("Uh-oh, google.com cert fingerprint ({0}) is unexpected. Cannot continue.",certificate.GetCertHashString());
        return false;
    }
Console.WriteLine("Unexpected SSL host, not continuing.");
return false;
}