简体   繁体   English

C# RestSharp 阻止请求重定向 302

[英]C# RestSharp prevent request redirect on 302

I'm trying to implement a third party service on my project and i need to do some authentication to consume their API.我正在尝试在我的项目上实现第三方服务,我需要进行一些身份验证才能使用他们的 API。

To do so i need to execute a POST request on their auth url, the problem is when i execute the request their server sends a response with a 302 and the Location header, now the weird part:为此,我需要在他们的身份验证 url 上执行 POST 请求,问题是当我执行请求时,他们的服务器发送带有 302 和 Location 标头的响应,现在是奇怪的部分:

I need to get this location link and read the query string to get the information i need.我需要获取此位置链接并阅读查询字符串以获取我需要的信息。

I have already tried everything i could think of, even Postman wont work with it.我已经尝试了我能想到的一切,即使邮递员也不会使用它。

This is my code:这是我的代码:

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

This is the response headers i managed to get using curl on the command prompt:这是我设法在命令提示符下使用 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

Is it possible ?可能吗 ?

You can disable RestSharp redirects with:您可以使用以下方法禁用 RestSharp 重定向:

client.FollowRedirects = false;

And then just check that response status code is 302 and read Location header.然后只需检查响应状态代码是否为 302 并读取 Location 标头。

对于新版本的 RestSharp:

  var client = new RestClient(new RestClientOptions(url) { FollowRedirects = false });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM