设置HttpClient的授权标题

我有一个HttpClient,我正在使用REST API。 但是我有麻烦设置授权标题。 我需要将标题设置为从我的OAuth请求收到的令牌。 我看到了一些.NET代码,

httpClient.DefaultRequestHeaders.Authorization = new Credential(OAuth.token); 

但是,WinRT中不存在Credential类。 任何人有任何想法如何设置授权标题?

所以做到这一点的方式是以下几点,

 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的代码似乎有点重复的代码。

我想有两种方法可以改善答案。

创build一个帮助类来创build客户端:

 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 } 

创build一个扩展方法:

不赢取美容奖品,但工程很好:)

  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上面的选项使客户端使用语句less一些重复。 请记住,如果您正在进行多个http调用,重用HttpClient是最佳做法,但是我认为这个问题有点超出范围。

使用System.Net.Http组件的AuthenticationHeaderValue

 public AuthenticationHeaderValue( string scheme, string parameter ) 

我们可以像这样为httpclient设置或更新现有的Authorization标头:

 httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TokenResponse.AccessToken); 

因为重用HttpClient实例是一个很好的做法 ,对于性能问题,并且因为没有答案给出这个解决scheme,所以我把这个链接放在了我对类似问题的答案上:

https://stackoverflow.com/a/40707446/717372

这可能有助于设置标题:

 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,我想这可以给你一个关于头和Ttypes如何工作的想法,如果你使用函数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; } } }