【发布时间】:2018-09-19 10:42:30
【问题描述】:
我有一个使用 IHostedService 从后端 cs 类调用 API 的应用程序。使用基本的 API 调用(“http://httpbin.org/ip”),它可以正常工作并返回正确的值,但是我现在需要调用 Siemens API,这需要我设置授权标头,并将“grant_type=client_credentials”放在正文中。
public async Task<string> GetResult()
{
string data = "";
string baseUrl = "https://<space-name>.mindsphere.io/oauth/token";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", {ServiceCredentialID: ServiceCredentialSecret});
using (HttpResponseMessage res = await client.GetAsync(baseUrl))
{
using (HttpContent content = res.Content)
{
data = await content.ReadAsStringAsync();
}
}
}
我认为我的标头设置正确,但在完整请求被格式化之前我无法确定。甚至可以将请求的正文设置为“grant_type=client_credentials”吗?
【问题讨论】:
-
当然可以。您需要将
client.SendAsync()与您设置内容的自定义请求消息一起使用。
标签: api asynchronous asp.net-core http-headers authorization