【问题标题】:C#.Net RestSharp client - passing auth tokenC#.Net RestSharp 客户端 - 传递身份验证令牌
【发布时间】:2018-06-26 22:03:27
【问题描述】:

我正在使用 RestSharp 在 C#.Net 中编写一个 REST 客户端。有两个 API 调用 - 一个是“Auth”调用,第二个是“getKey”调用。 “Auth”调用在响应中返回一个“Auth token”,我想从响应中解析该令牌,并将其作为标头传递给第二个“getkey”调用。请举例说明

【问题讨论】:

    标签: rest api restsharp


    【解决方案1】:

    我已经提供了一些示例来实现您的方案。请使用以下示例并根据您的要求进行修改。

    RestUtils 类:

    添加请求标头,如果您的应用程序需要一些附加标头。

     class RestUtils
        {
            private static readonly RestClient _restClient = new RestClient();
    
            public static void SetBaseURL(String host)
            {
                _restClient.BaseUrl = new Uri(host);
            }
    
            public static string GetResponse(String endpoint, String token)
            {
                var request = new RestRequest(endpoint, Method.GET);
                request.AddHeader("Accept", "application/json");
                request.AddHeader("Authorization", token);
                IRestResponse response = _restClient.Execute(request);
                return response.Content;
            }
    
            public static string GetToken(String endpoint)
            {
                var request = new RestRequest(endpoint, Method.GET);
                request.AddHeader("Accept", "application/json");
                IRestResponse response = _restClient.Execute(request);
                return response.Content;
            }
        }
    

    测试类:

    在您的测试类中,您可以添加以下步骤,您可以得到预期的结果。将执行前两行并将身份验证令牌作为输出。因此,您可以在后续行中将检索到的令牌用于其他 API。另一种方式,您可以创建一个属性类并设置检索到的令牌值。这样,您就可以从各个类访问令牌。

            //Specify the Base URI of your Token Specific API
            RestUtils.SetBaseURL("https://login.microsoftonline.com/");
            //Specify the End Point of your Token Specific API
            String token = RestUtils.GetToken("/oauth2/token");
    
            //Specify the Base URI of your actual Test API
            RestUtils.SetBaseURL("XXXXXXX");
            String response = RestUtils.GetResponse(token);
    

    【讨论】:

      猜你喜欢
      • 2019-06-16
      • 1970-01-01
      • 2013-08-19
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 2015-11-03
      • 2011-08-16
      相关资源
      最近更新 更多