繁体   English   中英

c# RestSharp:添加和删除 cookie 因为 Statuscode 403

[英]c# RestSharp: Adding and delete cookie because Statuscode 403

我目前正在尝试使用 RestSharp(版本 107.1.2)获取外部 API 的信息。 不幸的是,在每个请求中,我都会收到响应状态代码 403“禁止”。 我现在联系了提供商,他告诉我,首先删除所有 cookies,然后添加 cookie“SMCHALLENGE=YES”。

我在 RestSharp 中尝试过,但是在使用 client.AddCookie 扩展时,我收到了 ArgumentException。 我现在找到了另一种选择,在 header 中添加 cookie,但这也不起作用。

你有什么想法,如何删除所有 cookies 然后添加 SMCHALLENGE cookie?

  var client = new RestClient("https://test.de/api/token");
  string resource = null;
  client.Authenticator = new HttpBasicAuthenticator("testUser", "testPW");
  string apiKey = null;
  var request = new RestRequest(resource, Method.Get);

  //Following execution throws System.ArgumentException: "The {0} parameter cannot be an empty string. Parameter name: cookie.domain"
  //client.AddCookie("SMCHALLENGE", "YES");
  request.AddHeader("Cookie", "SMCHALLENGE=YES");

  var response = client.ExecuteAsync(request);
  response.Wait();
  RestResponse rr = response.Result;

非常感谢!

Cookies 不是标题。 您需要将RestClient添加到 RestClient 自己的 cookie 容器中。 响应中返回的 Cookies 也将在 cookie 容器中可用。 RestClient 上有一个RestClient作为快捷方式。

var client = new RestClient("https://test.de/api/token");
client.AddCookie("SMCHALLENGE", "YES");

您还可以使用 cookie 容器:

client.CookieContainer.Add(new Cookie(...));

您需要避免为每个请求创建一个新的RestClient实例。 这样,您还可以跨请求保留 cookies。

暂无
暂无

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

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