If I correctly understand you want to have an endpoint, which will make two POST
requests to third-party API. The first request will retrieve an Authorization Token. The second request will use the Token in its Headers to pass an authorization.
To achive this behavior, you should to have a single endpoint in your API, instead of two endpoints (as in your example above).
Also, I recommend you to have a separate class, which will responsible for communicating with your third-party API (with the postman.uipath.rocks
).
So, your single endpoint to call a third-party API may looks like this:
public class Controller
{
// another Controller's code...
private readonly IPostmanApi postmanApi;
public Controller(IPostmanApi postmanApi)
{
this.postmanApi = postmanApi;
}
[HttpPost]
public async Task<IActionResult> StartPostmanProcess()
{
string token = await postmanApi.GetToken();
await postmanApi.StartProcess(token);
return Accepted();
}
// another Controller's code...
}
Your IPostmanApi.cs
file may looks like this:
public interface IPostmanApi
{
///<summary>
/// A method to get Authorization Token from Postman
///</summary>
Task<string> GetToken();
///<summary>
/// A method to get start a process in Postman
///</summary>
///<param name="token">Postman's authorization token</param>
Task StartProcess(string token);
}
Your PostmanApi.cs
file may looks like this:
public class PostmanApi
{
Task<string> GetToken()
{
using (HttpClient client = new HttpClient())
{
var response = await client.PostAsync("https://postman.uipath.rocks/#8f3b38d8-57dc-4d79-876d-0d2ff897f61a");
// Note: this code assumes that the whole response body is a string Token.
// If the `postman.uipath.rocks` returns an JSON object, which contains a
// Token inside some field, you may use Newtonsoft.Json library to deserialize
// it, and then retrieve your Token from corresponding field.
// See example here: https://stackoverflow.com/questions/24131067/deserialize-json-to-array-or-list-with-httpclient-readasasync-using-net-4-0-ta
return await response.Content.ReadAsStringAsync();
}
}
Task StartProcess(string token)
{
using (HttpClient client = new HttpClient())
{
// Note: this code assumes that the `postman.uipath.rocks` receives
// a **Bearer** token. If it receives another kind of authentication
// scheme, you should use it instead of "Bearer".
client.DefaultRequestHeaders.Authorization
= new AuthenticationHeaderValue("Bearer", token);
await client.PostAsync("https://postman.uipath.rocks/#738c3beb-1c19-4257-8474-841a054c4220");
}
}
Also don't forget to register your IPostmanApi
service within Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
// another code...
services.AddScoped<IPostmanApi, PostmanApi>();
// another code...
}
Notice:
- This code is not thread-safe (because an
HttpClient
is not thread safe). If you want it to be thread-safe, consider to use IHttpClientFactory
.
Useful links: