简体   繁体   English

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

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

i am currently try to get information of an external API using RestSharp (Version 107.1.2).我目前正在尝试使用 RestSharp(版本 107.1.2)获取外部 API 的信息。 Unfortunately, in every request I get response Status Code 403 "Forbidden".不幸的是,在每个请求中,我都会收到响应状态代码 403“禁止”。 I now have contact to the provider and he told me, to delete all cookies first and then add the cookie "SMCHALLENGE=YES".我现在联系了提供商,他告诉我,首先删除所有 cookies,然后添加 cookie“SMCHALLENGE=YES”。

I tried this in RestSharp, but when using the client.AddCookie extension, I receive ArgumentException.我在 RestSharp 中尝试过,但是在使用 client.AddCookie 扩展时,我收到了 ArgumentException。 I now found another option, to add the cookie in header, but this doesn't work either.我现在找到了另一种选择,在 header 中添加 cookie,但这也不起作用。

Do you have an idea, how to delete all cookies and then add the SMCHALLENGE 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;

Thank you very much!非常感谢!

Cookies aren't headers. Cookies 不是标题。 You need to add your cookies to the RestClient own cookie container.您需要将RestClient添加到 RestClient 自己的 cookie 容器中。 Cookies that are returned in the response will also be available in the cookie container.响应中返回的 Cookies 也将在 cookie 容器中可用。 There's a function on RestClient to do that as a shortcut. RestClient 上有一个RestClient作为快捷方式。

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

You can also work with the cookie container:您还可以使用 cookie 容器:

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

You'd need to avoid creating a new RestClient instance for each request.您需要避免为每个请求创建一个新的RestClient实例。 This way you'd also keep the cookies across requests.这样,您还可以跨请求保留 cookies。

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

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