RESTSharp使用Cookie的GET调用

xjreopfe  于 2022-11-07  发布在  Postman
关注(0)|答案(2)|浏览(200)

使用RESTSharp,我可以登录:

RestClient client = new RestClient(Constants.APIURL + "method/login");
        CookieContainer cookieJar = new CookieContainer();
        RestRequest request = new RestRequest(Method.POST);
        client.CookieContainer = cookieJar;
        request.AddHeader("Content-Type", "application/json");
        request.AddHeader("Accept", "application/json");
        request.AddJsonBody(new
        {
            usr = username,
            pwd = password
        });

        var response = client.Execute(request);
        var cookie = HttpContext.Current.Server.UrlDecode(response.Headers.ToList().Find(x => x.Name == "Set-Cookie").Value.ToString());

然后,我存储cookie并发送到另一个API调用,也是通过RESTSharp。

RestClient client = new RestClient(Constants.APIURL);
        RestRequest request = new RestRequest("resource/Asset", Method.GET);
        request.AddCookie("Cookie", HttpContext.Current.Server.UrlEncode(cookie));

但是它一直返回403禁止。我试过 Postman ,它工作绝对正常。
有什么帮助吗?是不是我把饼干发错了?我试着用HttpWebRequest发送饼干,它工作得非常好。

0s0u357o

0s0u357o1#

我也试过复制粘贴一个从Postman生成的代码,其中cookie是在一个头中传递的,但它不起作用。
client.AddDefaultHeader("Cookie", cookie);

wnrlj8wa

wnrlj8wa2#

235 / 5.000 Resultados de traducción For RestSharp v107 and〉您可以使用CookieContainer,并在其中存储所有接收到的Cookie。然后将CookieContainer传递给RestClientOptions,并在示例化var client 1 = new RestClient(选项)时将其作为参数使用;
CookieContainer cookieJar =新建的Cookie容器(); cookieJar.Add(响应.Cookies);

var options1 = new RestClientOptions(UL.moodle_host + "login/index.php?")
        {
            ThrowOnAnyError = true,
            UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0",
            FollowRedirects = true,
            CookieContainer = cookieJar
        };   

        // new request TRY loging
        var client1 = new RestClient(options1);

相关问题