且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

调用HTTPClient.PostAsync时设置Authorization/Content-Type标头

更新时间:2022-06-15 22:15:32

添加标头的方法如下:

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");

或者,如果您需要一些自定义标头:

Or if you want some custom header:

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("HEADERNAME", "HEADERVALUE");

此答案已经有SO响应,请参见下文:

This answer has SO responses already, see below:

  • Adding headers when using httpClient.GetAsync
  • Setting Authorization Header of HttpClient

更新

似乎您要添加两个标题.授权和内容类型.

Seems you are adding two headerrs; authorization and content type.

string authValue = "NLAuth nlauth_account=5731597_SB1,nlauth_email=xxx@xx.com, nlauth_signature=Pswd1234567, nlauth_role=3";
string contentTypeValue = "application/json";

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authValue);
client.DefaultRequestHeaders.Add("Content-Type", contentTypeValue);