调用 Web API 的 Web API:调用 APIA web API that calls web APIs: Call an API

有了令牌后,就可以调用受保护的 Web API 了。After you have a token, you can call a protected web API. 可以从 Web API 的控制器执行此操作。You do this from the controller of your web API.

控制器代码Controller code

以下代码继续演示调用 Web API 的 Web API:获取应用的令牌中显示的示例代码。The following code continues the example code that's shown in A web API that calls web APIs: Acquire a token for the app. 该代码在 API 控制器的操作中调用。The code is called in the actions of the API controllers. 它调用名为“todolist” 的下游 API。It calls a downstream API named todolist.

获取令牌后,将其用作持有者令牌以调用下游 API。After you've acquired the token, use it as a bearer token to call the downstream API.

private async Task CallTodoListService(string accessToken)
{

// After the token has been returned by Microsoft Identity Web, add it to the HTTP authorization header before making the call to access the To Do list service.
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

// Call the To Do list service.
HttpResponseMessage response = await _httpClient.GetAsync(TodoListBaseAddress + "/api/todolist");
...
}

后续步骤Next steps