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;
}
}
Usage:
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}")));
}
}
Usage:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = _username.ToAuthHeaderValue(_password);
}
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;
}
3
这是我如何做到的:
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());
}
}
}
public AuthenticationHeaderValue(
string scheme,
string parameter
)
我们可以为 httpclient 设置或更新现有的 Authorization 标头,如下所示:
httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TokenResponse.AccessToken);
53
Use Basic Authorization And Json Parameters.
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();
}
11 回答
所以这样做的方法如下,
我寻找一个处理这个问题的好方法,我正在寻找同样的问题 . 希望这个答案能帮助每个遇到同样问题的人都喜欢我 .
来自https://www.theidentityhub.com/hub/Documentation/CallTheIdentityHubApi的参考
我同意TheWhiteRabbit的答案,但如果你使用HttpClient进行大量调用,我认为代码似乎有点重复 .
我认为有两种方法可以改善答案 .
创建一个帮助程序类来创建客户端:
Usage:
创建扩展方法:
不赢得美容奖但是效果很好:)
Usage:
我再次认为上面两个选项使客户端使用语句重复性降低一点 . 请记住,如果要进行多个http调用,最好重用HttpClient,但我认为这个问题有点超出了范围 .
因为它是一个 good practice to reuse the HttpClient instance ,对于性能和端口耗尽问题,并且因为没有一个答案给出了这个解决方案(甚至引导你走向不良做法:()),我在这里给出了我在类似问题上做出的答案的链接:
https://stackoverflow.com/a/40707446/717372
关于如何很好地使用HttpClient的一些消息来源:
https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
https://blogs.msdn.microsoft.com/alazarev/2017/12/29/disposable-finalizers-and-httpclient/
使用C#HttpClient设置基本身份验证 . 以下代码对我有用 .
这是我如何做到的:
这个you-tube视频帮了我很多忙 . 请检查一下 . https://www.youtube.com/watch?v=qCwnU06NV5Q
使用
AuthenticationHeaderValue
类的System.Net.Http
程序集我们可以为
httpclient
设置或更新现有的Authorization
标头,如下所示:Use Basic Authorization And Json Parameters.
这可能有用,如果你从服务接收json或xml,我想如果你使用函数MakeXmlRequest(把结果放在xmldocumnet中)和MakeJsonRequest,你可以让你知道 Headers 和T类型是如何工作的 . (将json放在你想要的类中,与json响应具有相同的结构)
这可能有助于设置 Headers :