【问题标题】:c# RestSharp: Adding and delete cookie because Statuscode 403c# RestSharp:添加和删除 cookie,因为 Statuscode 403
【发布时间】:2022-02-03 17:05:54
【问题描述】:

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

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

您有什么想法,如何删除所有 cookie,然后添加 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;

非常感谢!

【问题讨论】:

  • 我现在走得更远了,现在通过 Postman 让它工作了。显然,一个名为“SMSESSION”的cookie是通过“Interceptor”提前检索到的。然后,该值作为 cookie 在请求中传递。不幸的是,我还不知道如何在 c# 中的请求之前读取和传递这个 SMSESSION cookie。

标签: c# cookies httpclient restsharp


【解决方案1】:

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

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

您也可以使用 cookie 容器:

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

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

【讨论】:

  • 1) 第一个建议 client.AddCookie 抛出 System.ArgumentException: {0} 参数不能为空字符串。参数名:cookie.Domain 第二个就好了!我现在也收到了 SMSESSION cookie。谢谢!
  • 嗯,奇怪。 AddCookie 只是 CookieContainer.Add() 的包装。 cookie 容器的Add 函数确实检查了Domain 属性并抛出。我将添加域参数,感谢您报告此问题。
  • 嗨,Alexey,您对 RestSharp 编程有更详细的了解吗?我现在有另一个现象。如何使用 RestSharp 设置 ServicePoint.Expect100Continue 变量?我只有 RestSharp 之外的解决方案,使用“正常”HttpWebRequest:webRequest.ServicePoint.Expect100Continue = false; RestSharp 中是否有类似的可能?非常感谢!
  • 很抱歉,我从来不用Expect100Continue。 RestSharp 除了编写HttpRequestMessage,将其与HttpClient 一起发送并解析响应外,没有做任何其他事情。与HttpClient 相关的一切都应该与RestSharp 一起使用。我不确定HttpClient 是否尊重Expect100Continue 属性,但它可能。
  • 我添加了一个函数来配置头文件到最新的预发布包。你可以做client = new RestClient(options, headers => headers.ExpectContinue = false)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
  • 1970-01-01
  • 2011-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多