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

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

问题描述

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

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天全站免登陆