Vb.net 擅自退货

Vb.net 擅自退货,vb.net,restsharp,Vb.net,Restsharp,我有一个问题,我想我可能错过了与RestSharp的一些东西。 我正在授权并取回一块饼干,很好。。。见下文。但当我打电话获取数据时,它会返回未经授权的数据。它在Postman中工作得很好,但在下面的代码中不起作用。我正在使用一个控制台应用程序,我试图通过AddHeader、AddCookie发送cookie,并将其作为一个参数。responseLogin确实包含正确的cookie。任何帮助都会很好 Dim clientLogin = New RestClient("http://[URI

我有一个问题,我想我可能错过了与RestSharp的一些东西。 我正在授权并取回一块饼干,很好。。。见下文。但当我打电话获取数据时,它会返回未经授权的数据。它在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)
Cookie标头需要包含Cookie的名称和值,例如

Dim authCookie = responseLogin.Cookies(0) ' Probably should find by name
request.AddHeader("Cookie", String.Format("{0}={1}", authCookie.Name, authCookie.Value))
但是,我从未使用过RestSharp,我个人认为RestSharp自动支持cookies,因此,如果您重用RestClient实例并设置CookieContainer,则不需要手动处理cookies,除非您愿意,这在某些情况下可能更可取

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容器,而不是重用客户端。

我在RestClient.NET framework 4.5.2版本中也遇到了同样的问题。 事实证明,您必须实现IAAuthenticator接口

 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);
            
}
我这样做了,我的请求成功了