【问题标题】:C# RestSharp prevent request redirect on 302C# RestSharp 阻止请求重定向 302
【发布时间】:2017-10-03 03:16:28
【问题描述】:

我正在尝试在我的项目中实现第三方服务,我需要进行一些身份验证才能使用他们的 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

有可能吗?

【问题讨论】:

    标签: c# rest restsharp


    【解决方案1】:

    您可以使用以下方法禁用 RestSharp 重定向:

    client.FollowRedirects = false;
    

    然后只需检查响应状态码是否为 302 并读取 Location 标头。

    【讨论】:

    • 在新版RestSharp中,FollowRedirects被移到ClientOptions... 示例用法:client = new RestClient(new RestClientOptions() {FollowRedirects=false})
    • 在此处阅读更多关于弃用的信息restsharp.dev/v107/#restclient-and-options
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 2015-07-29
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    相关资源
    最近更新 更多