我正在尝试使用基本身份验证通过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");
将会通过,只有“授权”似乎被删除/丢失。
答案 0 :(得分:22)
而不是“手动”添加标题,请执行以下操作:
var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
client.Authenticator = new HttpBasicAuthenticator("UserA", "123");
答案 1 :(得分:9)
我使用了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 & " **")
关键是要确保在“持票人”这个词之后有一个空格。但这可能适用于任何类型的自定义令牌授权标头
答案 2 :(得分:4)
您必须使用 ParameterType.HttpHeader 参数:
request.AddParameter("Authorization", "data", ParameterType.HttpHeader);