如何在C#中使用RestClient处理嵌套查询

时间:2018-09-28 14:50:25

标签: c# rest request

我已经有以下代码可以发布请求:

string requestString = "https://api.bimobject.com/search/v1/products?Bearer_token=" + AccesToken + "&filter.brand.id="+BrandID;
var client = new RestClient(requestString);
var request = new RestRequest(Method.GET);
request.AddHeader("Cache-Control", "no-cache");


IRestResponse response = client.Execute(request);

现在,我想添加一个身份验证令牌,该身份验证令牌根据文档采用以下格式:

     "auth": {
        "bearer": [
           {
              "key": "token",
              "value": "374bfdca122189f8c98e41ccd7a30212",
              "type": "string"
           }
        ],
        "type": "bearer"
     },

现在我不确定如何实际执行此操作,它似乎是一个嵌套参数,但实际上我不知道如何添加这样的嵌套参数。我已经看到了

request.AddParameter("auth:bearer:[key:token,value:374bfdca122189f8c98e41ccd7a30212,type:string])

那么我该怎么做呢?

2 个答案:

答案 0 :(得分:2)

也许您必须像这样通过HTTP标头传递令牌:

left

关于您要完成的工作的任何其他上下文都将很好,例如,如果您查询的服务是免费的,或者POST请求需要请求主体中的令牌,则指向文档的一些链接

答案 1 :(得分:2)

基于示例中的示例标记,并假设该值存储在AccessToken变量中,

您需要做的就是将Authorization标头添加到请求中。

string requestString = "https://api.bimobject.com/search/v1/products?filter.brand.id=" + BrandID;
var client = new RestClient(requestString);
var request = new RestRequest(Method.GET);
request.AddHeader("Cache-Control", "no-cache");
//Assuming AccessToken = 374bfdca122189f8c98e41ccd7a30212 value in sample JSON
request.AddHeader("Authorization", $"Bearer {AccessToken}");

IRestResponse response = client.Execute(request);

如果重用客户端,则另一种选择是创建一个IAuthenticator派生类

public class BearerAuthenticator : IAuthenticator {
    private readonly string authHeader;

    public BearerAuthenticator(string accessToken) {
        if (accessToken == null)
            throw new ArgumentNullException("accessToken");

        authHeader = $"Bearer {accessToken}";
    }

    public void Authenticate(IRestClient client, IRestRequest request) {
        // only add the Authorization parameter if it hasn't been added by a previous Execute
        if (!request.Parameters.Any(p => p.Type.Equals(ParameterType.HttpHeader) &&
                                         p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase)))
            request.AddParameter("Authorization", authHeader, ParameterType.HttpHeader);
    }
}

并将其分配给客户端

string requestString = "https://api.bimobject.com/search/v1/products?filter.brand.id=" + BrandID;
var client = new RestClient(requestString);
client.Authenticator = new BearerAuthenticator(AccessToken);

var request = new RestRequest(Method.GET);
request.AddHeader("Cache-Control", "no-cache");

IRestResponse response = client.Execute(request);

现在,Authorization标头将被添加到该客户端发出的所有请求中(前提是该请求尚未设置该标头)