这就是我做到的方式:
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()); } } }
这个you-tube视频帮了我很多忙。请检查一下。 https://www.youtube.com/watch?v=qCwnU06NV5Q
所以这样做的方法如下,
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");
我正在设置持票人令牌httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Bearer”,令牌);
它在一个端点工作,但不是另一个端点。问题是我在“持票人”上有小写“b”。改变后现在它适用于我正在击打的两个api。如果你甚至不把它看作是寻找针头的大海捞针之一,这么容易被遗漏。
确保拥有“持票人” - 有资本。
request.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String( System.Text.ASCIIEncoding.ASCII.GetBytes( string.Format("{0}:{1}", "yourusername", "yourpwd"))));
的 使用基本授权和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(); }
因为它是一个 的 重用HttpClient实例的好习惯 强> ,为 性能和端口耗尽问题 ,因为没有一个答案给出这个解决方案(甚至引导你走向不良做法:()),我在这里给出了一个链接,我在一个类似的问题上做出了回答:
https://stackoverflow.com/a/40707446/717372
关于如何充分利用HttpClient的一些消息来源:
运用 AuthenticationHeaderValue 一类 System.Net.Http 部件
AuthenticationHeaderValue
System.Net.Http
public AuthenticationHeaderValue( string scheme, string parameter )
我们可以设置或更新现有的 Authorization 我们的标题 httpclient 像这样:
Authorization
httpclient
httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TokenResponse.AccessToken);
使用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; }
这可能有助于设置标题:
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,我想如果你使用函数MakeXmlRequest(把结果放在xmldocumnet中)和MakeJsonRequest,你可以让你知道标题和T类型是如何工作的。 (将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; } } }
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); } }