【问题标题】:Asp.Net Core - Making API calls from backendAsp.Net Core - 从后端进行 API 调用
【发布时间】: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


【解决方案1】:

据我从 Siemens API 文档中可以看出,他们期望表单数据,所以应该是这样的:

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});

        var formContent = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "client_credentials")
        });

        using (HttpResponseMessage res = await client.PostAsync(baseUrl, formContent))
        {

            using (HttpContent content = res.Content)
            {    
                data = await content.ReadAsStringAsync();
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2015-10-07
    • 2019-04-27
    • 2019-08-16
    • 2018-10-29
    • 2022-11-04
    • 1970-01-01
    • 2019-08-12
    • 2022-01-05
    • 2020-10-22
    相关资源
    最近更新 更多