我有我使用使用REST API一个HttpClient的。 但是我无法建立Authorization头。 我需要设置的头,我从做我的OAuth请求接收的令牌。 我看到了.NET一些代码,提出以下建议,
httpClient.DefaultRequestHeaders.Authorization = new Credential(OAuth.token);
然而凭证类这是否不存在WinRT中。 任何人有任何想法如何设置授权头?
我有我使用使用REST API一个HttpClient的。 但是我无法建立Authorization头。 我需要设置的头,我从做我的OAuth请求接收的令牌。 我看到了.NET一些代码,提出以下建议,
httpClient.DefaultRequestHeaders.Authorization = new Credential(OAuth.token);
然而凭证类这是否不存在WinRT中。 任何人有任何想法如何设置授权头?
因此,要做到这一点的方法如下,
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "Your Oauth token");
request.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "yourusername", "yourpwd"))));
我找了一个很好的方式来处理这个问题,我在看同样的问题。 希望这个答案将帮助大家谁都有同样的问题,喜欢我。
using (var client = new HttpClient())
{
var url = "https://www.theidentityhub.com/{tenant}/api/identity/v1";
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var response = await client.GetStringAsync(url);
// Parse JSON response.
....
}
从参考https://www.theidentityhub.com/hub/Documentation/CallTheIdentityHubApi
我同意TheWhiteRabbit的答案,但如果你有很多使用的HttpClient调用的代码似乎有点在我看来重复。
我认为有2种方式,以提高回答了一下。
public static class ClientHelper
{
// Basic auth
public static HttpClient GetClient(string username,string password)
{
var authValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}")));
var client = new HttpClient(){
DefaultRequestHeaders = { Authorization = authValue}
//Set some other client defaults like timeout / BaseAddress
};
return client;
}
// Auth with bearer token
public static HttpClient GetClient(string token)
{
var authValue = new AuthenticationHeaderValue("Bearer", token);
var client = new HttpClient(){
DefaultRequestHeaders = { Authorization = authValue}
//Set some other client defaults like timeout / BaseAddress
};
return client;
}
}
用法:
using(var client = ClientHelper.GetClient(username,password))
{
//Perform some http call
}
using(var client = ClientHelper.GetClient(token))
{
//Perform some http call
}
没有赢得美奖,但伟大工程:)
public static class HttpClientExtentions
{
public static AuthenticationHeaderValue ToAuthHeaderValue(this string username, string password)
{
return new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.Encoding.ASCII.GetBytes(
$"{username}:{password}")));
}
}
用法:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = _username.ToAuthHeaderValue(_password);
}
再次,我觉得2个以上选项中做出using语句少一点重复的客户端。 请记住,这是重用HttpClient的,如果你正在多个HTTP调用最好的做法,但我认为这是一个有点超出范围了这个问题。
由于这是一个很好的做法重用HttpClient的实例 ,对性能和端口耗尽的问题 ,因为没有一个答案给这个解决方案(甚至导致你走向不好的做法:(),我把这里对我做出了回答链接在一个类似的问题:
https://stackoverflow.com/a/40707446/717372
如何用好HttpClient的一些消息:
要设置基本身份验证使用C#的HttpClient。 下面的代码为我工作。
using (var client = new HttpClient())
{
var webUrl ="http://localhost/saleapi/api/";
var uri = "api/sales";
client.BaseAddress = new Uri(webUrl);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.ConnectionClose = true;
//Set Basic Auth
var user = "username";
var password = "password";
var base64String =Convert.ToBase64String( Encoding.ASCII.GetBytes($"{user}:{password}"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",base64String);
var result = await client.PostAsJsonAsync(uri, model);
return result;
}
这就是我已经做到了:
using (HttpClient httpClient = new HttpClient())
{
Dictionary<string, string> tokenDetails = null;
var messageDetails = new Message { Id = 4, Message1 = des };
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:3774/");
var login = new Dictionary<string, string>
{
{"grant_type", "password"},
{"username", "sa@role.com"},
{"password", "lopzwsx@23"},
};
var response = client.PostAsync("Token", new FormUrlEncodedContent(login)).Result;
if (response.IsSuccessStatusCode)
{
tokenDetails = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Content.ReadAsStringAsync().Result);
if (tokenDetails != null && tokenDetails.Any())
{
var tokenNo = tokenDetails.FirstOrDefault().Value;
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + tokenNo);
client.PostAsJsonAsync("api/menu", messageDetails)
.ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
}
}
}
这个你管视频帮了我很多。 请检查一下。 https://www.youtube.com/watch?v=qCwnU06NV5Q
使用基本授权和JSON参数。
using (HttpClient client = new HttpClient())
{
var request_json = "your json string";
var content = new StringContent(request_json, Encoding.UTF8, "application/json");
var authenticationBytes = Encoding.ASCII.GetBytes("YourUsername:YourPassword");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(authenticationBytes));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var result = await client.PostAsync("YourURL", content);
var result_string = await result.Content.ReadAsStringAsync();
}
使用AuthenticationHeaderValue
类的System.Net.Http
组装
public AuthenticationHeaderValue(
string scheme,
string parameter
)
我们可以设置或更新现有Authorization
头为我们httpclient
像这样:
httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TokenResponse.AccessToken);
6年后但如果添加此它可以帮助别人。
https://www.codeproject.com/Tips/996401/Authenticate-WebAPIs-with-Basic-and-Windows-Authen
var authenticationBytes = Encoding.ASCII.GetBytes("<username>:<password>");
using (HttpClient confClient = new HttpClient())
{
confClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(authenticationBytes));
confClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Constants.MediaType));
HttpResponseMessage message = confClient.GetAsync("<service URI>").Result;
if (message.IsSuccessStatusCode)
{
var inter = message.Content.ReadAsStringAsync();
List<string> result = JsonConvert.DeserializeObject<List<string>>(inter.Result);
}
}
我设置了承载令牌
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
它是在一个端点的工作,而不是其他。 问题是,我不得不小写b
的"bearer"
。 变更后,现在它适用于这两种API的我打。 这样一件容易的事情错过,如果你不甚至考虑它的草堆中寻找针的一个。
确保有"Bearer"
-资本。
这可以帮助设置页眉:
WebClient client = new WebClient();
string authInfo = this.credentials.UserName + ":" + this.credentials.Password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
client.Headers["Authorization"] = "Basic " + authInfo;
这可能工作,如果您收到一个JSON或从服务的XML,我认为这可以给大家介绍一下头和T型的工作原理也一样,如果你使用的功能MakeXmlRequest(把结果xmldocumnet)的想法和MakeJsonRequest (把JSON在您希望具有相同的结构,该JSON响应类)在接下来的方式
/*-------------------------example of use-------------*/
MakeXmlRequest<XmlDocument>("your_uri",result=>your_xmlDocument_variable = result,error=>your_exception_Var = error);
MakeJsonRequest<classwhateveryouwant>("your_uri",result=>your_classwhateveryouwant_variable=result,error=>your_exception_Var=error)
/*-------------------------------------------------------------------------------*/
public class RestService
{
public void MakeXmlRequest<T>(string uri, Action<XmlDocument> successAction, Action<Exception> errorAction)
{
XmlDocument XMLResponse = new XmlDocument();
string wufooAPIKey = ""; /*or username as well*/
string password = "";
StringBuilder url = new StringBuilder();
url.Append(uri);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url.ToString());
string authInfo = wufooAPIKey + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Timeout = 30000;
request.KeepAlive = false;
request.Headers["Authorization"] = "Basic " + authInfo;
string documento = "";
MakeRequest(request,response=> documento = response,
(error) =>
{
if (errorAction != null)
{
errorAction(error);
}
}
);
XMLResponse.LoadXml(documento);
successAction(XMLResponse);
}
public void MakeJsonRequest<T>(string uri, Action<T> successAction, Action<Exception> errorAction)
{
string wufooAPIKey = "";
string password = "";
StringBuilder url = new StringBuilder();
url.Append(uri);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url.ToString());
string authInfo = wufooAPIKey + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Timeout = 30000;
request.KeepAlive = false;
request.Headers["Authorization"] = "Basic " + authInfo;
// request.Accept = "application/json";
// request.Method = "GET";
MakeRequest(
request,
(response) =>
{
if (successAction != null)
{
T toReturn;
try
{
toReturn = Deserialize<T>(response);
}
catch (Exception ex)
{
errorAction(ex);
return;
}
successAction(toReturn);
}
},
(error) =>
{
if (errorAction != null)
{
errorAction(error);
}
}
);
}
private void MakeRequest(HttpWebRequest request, Action<string> successAction, Action<Exception> errorAction)
{
try{
using (var webResponse = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(webResponse.GetResponseStream()))
{
var objText = reader.ReadToEnd();
successAction(objText);
}
}
}catch(HttpException ex){
errorAction(ex);
}
}
private T Deserialize<T>(string responseBody)
{
try
{
var toReturns = JsonConvert.DeserializeObject<T>(responseBody);
return toReturns;
}
catch (Exception ex)
{
string errores;
errores = ex.Message;
}
var toReturn = JsonConvert.DeserializeObject<T>(responseBody);
return toReturn;
}
}
}