简体   繁体   中英

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). Unfortunately, in every request I get response Status Code 403 "Forbidden". I now have contact to the provider and he told me, to delete all cookies first and then add the cookie "SMCHALLENGE=YES".

I tried this in RestSharp, but when using the client.AddCookie extension, I receive ArgumentException. I now found another option, to add the cookie in header, but this doesn't work either.

Do you have an idea, how to delete all cookies and then add the 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. You need to add your cookies to the RestClient own cookie container. Cookies that are returned in the response will also be available in the cookie container. There's a function on RestClient to do that as a shortcut.

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

You can also work with the cookie container:

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

You'd need to avoid creating a new RestClient instance for each request. This way you'd also keep the cookies across requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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