繁体   English   中英

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

[英]How do I send an HTTP POST with HTTP Basic Authorization in ASP.NET Core?

我正在尝试在我的 ASP.NET Core MVC 应用程序中使用 Reddit API ( https://github.com/reddit-archive/reddit/wiki/OAuth2 ),为了获得一个令牌,我必须向一个 POST带有 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;
}

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

您需要创建格式为: username:password的 base64 编码字符串。 然后将其添加到 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));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM