C#RestSharp阻止请求重定向302

时间:2017-07-26 18:37:29

标签: c# rest restsharp

我正在尝试在我的项目上实施第三方服务,我需要进行一些身份验证才能使用他们的API。

为此我需要在他们的auth url上执行POST请求,问题是当我执行请求时,他们的服务器发送一个带有302和Location头的响应,现在是奇怪的部分:

我需要获取此位置链接并阅读查询字符串以获取我需要的信息。

我已经尝试过所有我能想到的东西,即使Postman也不会使用它。

这是我的代码:

var client = new RestClient(APIBase + "/portal/rest/oauth2/login");

var request = new RestRequest(Method.POST);

request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("cache-control", "no-cache");
request.AddParameter("application/x-www-form-urlencoded", $"user={User}&password={Password}&client_id={ClientId}", ParameterType.RequestBody);

var content = client.Execute(request);

这是我设法在命令提示符下使用curl的响应头:

HTTP/1.1 302 Moved Temporarily
Date: Wed, 26 Jul 2017 17:59:32 GMT
Server: Apache-Coyote/1.1
Location: LOCATION-LINK
Content-Length: 0

HTTP/1.1 200 OK
Date: Wed, 26 Jul 2017 17:59:32 GMT
Server: Apache-Coyote/1.1
Accept-Ranges: bytes
ETag: W/"20095-1497998126000"
Last-Modified: Tue, 20 Jun 2017 22:35:26 GMT
Content-Type: text/html
Content-Length: 20095
Vary: Accept-Encoding

有可能吗?

1 个答案:

答案 0 :(得分:3)

您可以使用以下命令禁用RestSharp重定向:

client.FollowRedirects = false;

然后检查响应状态代码是否为302并读取位置标题。