1

我在使用 REST 服务时遇到了一些问题,想弄清楚我在实现中缺少什么。

https://<server-name-or-address>/api/sessions

如果我使用 cURL 调用这个 rest api,它可以通过以下脚本正常工作

curl -i -k -H "Accept:application/*+xml;version=1.5" -u username:password -X POST https://<server-name-or-address>/api/sessions

但是,它根本不适用于 C# asp.net。我不确定我在这里缺少什么。这是我的尝试:

1) 使用 HTTP Web 请求

Uri address = new Uri(url);
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.Accept = "application/*+xml;version=1.5";

request.Credentials = new NetworkCredential(username,password);

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

// 调用上述语句时引发以下异常底层连接已关闭:无法为 SSL/TLS 安全通道建立信任关系。

2) 使用 Hammock.net

Hammock.RestClient client = new Hammock.RestClient();
string encodedAPIKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)));
client.AddHeader("Accept", "application/*+xml;version=1.5");
client.AddHeader("Authorization", "Basic " + username + ":" + password);
client.Authority = url;
Hammock.RestRequest req = new Hammock.RestRequest();
req.Path = url;
Hammock.RestResponse response = client.Request(req);
string _result = client.Request(req).Content; // exception

3) 使用 RestSharp

string _loginInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)));
RestSharp.RestClient client = new RestSharp.RestClient();
client.AddDefaultHeader("Accept", "application/*+xml;version=1.5");
client.AddDefaultHeader("Authorization", "Basic " + _loginInfo);
client.BaseUrl = url;
RestSharp.RestRequest request = new RestSharp.RestRequest();
request.AddUrlSegment("method", "POST");
request.AddUrlSegment("uri", url);
string result = client.Execute(request).Content;

我也尝试过使用 HttpClient、WebRequest、WebClient,但似乎没有任何效果。

4

1 回答 1

1

尝试在 HTTP 请求中手动设置 Authorization 标头。

string credentials = String.Format("{0}:{1}", username, password);
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("Basic ", base64);
request.Headers.Add("Authorization", authorization);

编辑:

看起来好像可能是由于自签名、过期或其他无效证书。尝试以下

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

从这个 SO 收集:https ://stackoverflow.com/questions/5595049/servicepointmanager-servercertificatevalidationcallback-question

于 2012-06-28T20:14:57.400 回答