我遇到了一个问题,并认为我可能会遗漏一些RestSharp。 我正在授权并回复一个cookie就好了......见下文。但是当我打电话来获取数据时,它会返回未经授权的数据。它在Postman中运行得很好,但在下面的代码中没有。我正在使用控制台应用程序,我试图通过AddHeader,AddCookie发送cookie,并作为参数。 responseLogin确实包含正确的cookie。任何帮助都会很棒。
Dim clientLogin = New RestClient("http://[URI to Authorize]............")
Dim requestLogin = New RestRequest(Method.POST)
requestLogin.AddParameter("application/x-www-form-urlencoded", "[Username and password here.....]", ParameterType.RequestBody)
Dim responseLogin As IRestResponse = clientLogin.Execute(requestLogin)
Dim client = New RestClient("http://[URI to get data]............")
Dim request = New RestRequest(Method.GET)
request.AddHeader("Cookie", responseLogin.Cookies(0).Value.ToString)
request.AddHeader("Accept", "application/json")
Dim response As IRestResponse = client.Execute(request)
答案 0 :(得分:0)
Cookie
标头需要包含cookie的名称和值,例如
Dim authCookie = responseLogin.Cookies(0) ' Probably should find by name
request.AddHeader("Cookie", String.Format("{0}={1}", authCookie.Name, authCookie.Value))
然而,the documentation(我从未亲自使用过RestSharp)说RestSharp自动支持cookie,所以如果你重用RestClient
实例并设置CookieContainer
你就不应该'我需要做任何事情来手动处理cookie(除非你想要,在某些情况下可能更好)。
Dim client = New RestClient(New Uri("[Base URI...]"))
client.CookieContainer = New System.Net.CookieContainer()
Dim requestLogin = New RestRequest("[login page path]", Method.POST)
requestLogin.AddParameter("application/x-www-form-urlencoded", "[Username and password here.....]", ParameterType.RequestBody)
Dim responseLogin As IRestResponse = client.Execute(requestLogin)
Dim request = New RestRequest("[data api path", Method.GET)
request.AddHeader("Accept", "application/json")
Dim response As IRestResponse = client.Execute(request)
您可能只是重复使用不同RestClient
个实例的Cookie容器,而不是重用client
。
答案 1 :(得分:0)
我在 RestClient .NET 框架 4.5.2 版本上遇到了同样的问题。 事实证明,您必须实现 IAuthenticator 接口。
public class MyAuth : IAuthenticator
{
readonly string _password;
readonly string _passwordKey;
readonly string _username;
readonly string _usernameKey;
public MyAuth(string usernameKey, string username, string passwordKey, string password)
{
_usernameKey = usernameKey;
_username = username;
_passwordKey = passwordKey;
_password = password;
}
public void Authenticate(IRestClient client, IRestRequest request)
=> request
.AddCookie(_usernameKey, _username)
.AddCookie(_passwordKey, _password);
//.AddParameter(_usernameKey, _username)
//.AddParameter(_passwordKey, _password);
}
我做到了,我的要求奏效了。