在重定向期间在 RestSharp 中保留授权标头 [英] Retaining authorization header in RestSharp during redirects

查看:45
本文介绍了在重定向期间在 RestSharp 中保留授权标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 RestSharp 进行 GET api 调用.api 调用通过传递授权标头通过 HTTP 基本身份验证进行身份验证.

I am using RestSharp to make a GET api call. The api call is authenticated through HTTP Basic authentication by passing the authorization header.

服务器使用状态代码 307 重定向 api 调用.我的客户端代码确实处理了重定向,但授权标头没有传递给这个重定向的 api 调用.如此处所述,这样做是有正当理由的.因此,我确实收到了未经授权的错误.

The server redirects the api call with a status code 307. My client code does handle the redirects but the authorization header is not passed to this redirected api call. This is done for valid reasons as mentioned here. Hence I do get an unauthorized error.

如何配置 RestClient 来恢复授权标头?

How can I configure the RestClient to restore the authorization header?

var client = new RestClient("https://serverurl.com");
var request = new RestRequest(Method.GET);

request.AddHeader("Authorization", "Basic Z3JvdXAxOlByb2otMzI1");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Tenant-Id", "4892");

IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

推荐答案

我添加了一个检查,使用以下代码重新发送接收 401 的 api 请求.

I added a check that resends the api request of receiving a 401 with the below code.

var client = new RestClient("https://serverurl.com");
var request = new RestRequest(Method.GET);

request.AddHeader("Authorization", "Basic Z3JvdXAxOlByb2otMzI1");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Tenant-Id", "4892");

IRestResponse response = client.Execute(request);

//Resend the request if we get 401
int numericStatusCode = (int)response.StatusCode;
if(numericStatusCode == 401) {
    var redirectedClient = new RestClient(response.ResponseUri.ToString());
    IRestResponse newResponse = redirectedClient.Execute(request);
    Console.WriteLine(newResponse.ResponseStatus);
}

这篇关于在重定向期间在 RestSharp 中保留授权标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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