如何在 ASP.NET Core 中发送具有 HTTP 基本授权的 HTTP POST?

Mer*_*n04 5 c# post authorization http asp.net-core

我正在尝试在 ASP.NET Core MVC 应用程序中使用 Reddit API ( https://github.com/reddit-archive/reddit/wiki/OAuth2 ),并且要获取令牌,我必须向具有 HTTP 基本授权的 URI(用户名和密码是客户端 ID 和密码)。目前我使用这段代码:

public async Task<HttpResponseMessage> HttpPost(string uri, string value)
{
    HttpClient httpClient = new HttpClient();
    HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri, new StringContent(value));
    return httpResponseMessage;
}
Run Code Online (Sandbox Code Playgroud)

但是,这不使用授权。如何添加授权?HttpClient.PostAsync我尝试查看和的文档HttpContent,但没有看到任何相关内容。

Kri*_*ana 13

您将需要创建一个格式为 base64 编码的字符串:username:password。然后将其添加到 Http 请求的授权标头中。

例子:

using (var client = new HttpClient { BaseAddress = new Uri("https://baseUrl") })
{
 var authString = Convert.ToBase64String(Encoding.UTF8.GetBytes("username:password"));

 client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authString);
 var response = await client.PostAsync(requestUri, new StringContent(value));
}
Run Code Online (Sandbox Code Playgroud)