Asp.Net Core-从后端进行API调用

时间:2018-09-19 10:42:31

标签: api asynchronous asp.net-core http-headers authorization

我有一个应用程序,它使用IHostedService从后端CS类调用API。通过基本的API调用(“ http://httpbin.org/ip”,它可以正常工作并返回正确的值,但是我现在需要调用Siemens API,这需要我设置一个Authorization标头,并将“ 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”吗?

1 个答案:

答案 0 :(得分:0)

据我从Siemens API文档中可以看到,他们希望使用Form数据,所以应该像这样:

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