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

本文关键字:RestSharp 何进行 排除 故障 curl 命令 | 更新日期: 2023-09-27 18:28:27

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

有没有一种方法可以查看正在发送和接收的标头,以及确切的URL?

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

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上找到一些关于mono标签的(更高级的)问题,所以它应该可以工作。(?)

如果用户名/密码真的有问题,我想我会得到403状态,而不是零状态?

附言:如果重要的话,我的其余脚本是:

using System;
using System.Net;
using RestSharp;
namespace webtest
{
    class MainClass
    {
        public static void Main (string[] args)
        {
        ...(above code)
        }
    }
}

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

关于故障排除

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

  • 试着注释掉Authenticator行,看看是否有什么变化(在我的情况下没有)
  • 尝试http://google.com
  • 尝试https://google.com

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

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

关于移植curl命令

默认情况下,linux上的curl使用它在/etc/ssl/certs中找到的证书。Mono的一揽子等效方法是执行mozroots --import --ask-remove,它将导入所有证书(请参阅Mono安全常见问题解答)。

另一种方法是将其放在程序的顶部:

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