Retaining authorization header in RestSharp during redirects

戏子无情 提交于 2019-12-08 04:55:17

问题


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

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.

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

回答1:


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


来源:https://stackoverflow.com/questions/53374247/retaining-authorization-header-in-restsharp-during-redirects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!