调用其他外部API的.Net核心Web API [英] .Net core Web API who calls other external APIs

查看:74
本文介绍了调用其他外部API的.Net核心Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建.Net Core Web API,它将进一步调用外部API.

I'm creating a .Net Core web API which will further call an external API.

场景:

在.Net Core Web API中,我想向UiPath Orchestrator API发出发布请求以获取身份验证令牌.以下是我要提出的请求的链接 https://postman.uipath.rocks/#8f3b38d8-57dc-4d79-876d-0d2ff897f61a

In .Net Core web API, I want to make a Post request to UiPath Orchestrator API to get authentication token. Following is the link for the Request that I want to make https://postman.uipath.rocks/#8f3b38d8-57dc-4d79-876d-0d2ff897f61a

[HttpPost]
public Task<IActionResult> GetAccessToken()
{
  //Here I want to make a Post request to the API to Authenticate
}

此响应(Auth令牌)将发送到另一个发布请求以启动流程 https://postman.uipath.rocks/#738c3beb-1c19-4257-8474-841a054c4220

And response (Auth token) of this will be sent to another post request to start a process https://postman.uipath.rocks/#738c3beb-1c19-4257-8474-841a054c4220

[HttpPost]
 public Task<IActionResult> StartProcess(string token)
 {
   //Here I want to make a Post request to the other API in which token from the previous call will be 
    sent in header
 }

我必须在一两天内完成它,但我不知道该如何实现.

I have to complete it in a day or two and I can't figure out how can I achieve this.

任何帮助将不胜感激.

推荐答案

如果我正确理解您想要一个终结点,该终结点将向第三方API发出两个 POST 请求.第一个请求将检索一个授权令牌.第二个请求将在其标头中使用 Token 来传递授权.

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.

要实现此行为,您应该在API中具有单个终结点,而不是两个终结点(如上面的示例).

To achive this behavior, you should to have a single endpoint in your API, instead of two endpoints (as in your example above).

此外,我建议您有一个单独的类,该类负责与您的第三方API(通过 postman.uipath.rocks )进行通信.

Also, I recommend you to have a separate class, which will responsible for communicating with your third-party API (with the postman.uipath.rocks).

因此,您的调用第三方API的单个端点可能看起来像这样:

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...
}

您的 IPostmanApi.cs 文件可能如下所示:

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

您的 PostmanApi.cs 文件可能如下所示:

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

也不要忘记在 Startup.cs 中注册您的 IPostmanApi 服务:

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...
}

通知:

  1. 此代码不是线程安全的(因为 HttpClient 不是线程安全的).如果希望它是线程安全的,请考虑使用 IHttpClientFactory .
  1. 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.

有用的链接:

这篇关于调用其他外部API的.Net核心Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆