26

我正在尝试使用基本身份验证通过 HTTPS 调用本地托管的 WCF REST 服务。

这有效,授权标头通过就好了,一切都很高兴:

ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var request = (HttpWebRequest)WebRequest.Create("https://localhost/MyService/MyService.svc/");
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add(
  System.Net.HttpRequestHeader.Authorization,
  "Basic " + this.EncodeBasicAuthenticationCredentials("UserA", "123"));

WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
    if (webStream != null)
    {
        using (StreamReader responseReader = new StreamReader(webStream))
        {
            string response = responseReader.ReadToEnd();
        }
    }
}

然而,当我尝试使用 RestSharp 时,Authorization 标头永远不会出现在请求中:

ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;

var credentials = this.EncodeBasicAuthenticationCredentials("UserA", "123");

var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");   
var restRq = new RestSharp.RestRequest("/");
restRq.Method = Method.GET;
restRq.RootElement = "/";
restRq.AddHeader("Authorization", "Basic " + credentials);
var restRs = client.Execute(restRq);

我对 RestSharp 方法做错了什么?

我知道 AddHeader 方法有效,因为:

restRq.AddHeader("Rum", "And Coke");

将通过,只有“授权”似乎被剥离/丢失。

4

3 回答 3

34

而不是“手动”添加标题,请执行以下操作:

var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
client.Authenticator = new HttpBasicAuthenticator("UserA", "123");
于 2013-07-20T14:03:27.513 回答
14

我使用 milano 的答案让我的 REST 服务调用正常工作(使用 GET)

    Dim client2 As RestClient = New RestClient("https://api.clever.com")

    Dim request2 As RestRequest = New RestRequest("me", Method.GET)

    request2.AddParameter("Authorization", "Bearer " & j.access_token, ParameterType.HttpHeader)

    Dim response2 As IRestResponse = client2.Execute(request2)
    Response.Write("** " & response2.StatusCode & "|" & response2.Content & " **")

关键是确保在“Bearer”之后有一个空格,但这可能适用于任何类型的自定义令牌授权标头

于 2016-09-14T15:29:29.733 回答
6

您必须使用ParameterType.HttpHeader参数:

request.AddParameter("Authorization", "data", ParameterType.HttpHeader);
于 2014-05-10T14:32:50.907 回答