我正在尝试登录供应商的网站以下载文件。我不是真正的开发人员,但要学习足够多的知识,通常能够适应我发现的适合我们情况的代码示例。在这种情况下,我三年前编写的代码可以正常工作,直到供应商今年更改身份验证为止。我一直在使用RestSharp 105.2.3(无法升级,因为我们的服务器运行VS 2010,但我无权对此进行更改)。问题是新的身份验证不再沿着“基本URL”进行,在此版本的RestSharp中,请求似乎附加在基本URL上,因此在这种情况下,我开始收到404错误。
我发现this article与添加自定义身份验证器有关。这似乎使我了解其中的一部分:如果我查看响应内容的“文本可视化工具”,则会发现它是预期的形式。查看客户端对象时,我看到了类似的身份验证Cookie,当我手动登录以查看API期望时会在Postman中看到。该URL具有一个身份验证密钥(很快就会过期),该密钥与我在Postman中观察到的相似。
所以,我想我想做的只是将响应用作新请求,通过像过去一样添加用户名和密码参数来修改它。这样可以避免RestSharp将新URL附加到基本URL的问题(我认为)。
// This is the API base URL:
var apiURL = "https://api.testingVendor.com/";
var lclient = new RestClient(apiURL);
lclient.CookieContainer = new CookieContainer();
// I submit a request for the data file initially in order to be
//issued a new session ID:
var EstablishSession = new RestRequest("reports/DownloadYourData#/?assmt=11", Method.GET);
// These headers all came from what I observed in Postman
EstablishSession
.AddHeader("cache-control", "no-cache")
.AddHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3")
.AddHeader("dnt", "1")
.AddHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36")
.AddHeader("upgrade-insecure-requests", "1");
IRestResponse response = lclient.Execute(EstablishSession);
// At this point the response is the appropriate form to log in. With
//the new session ID embedded in the response URL, I now prepare to attempt
//log in with a new client that is modified to capture authentication redirects:
var resp_URL = response.ResponseUri.ToString();
var username = "xxxx";
var pw = "xxxx";
var client = new RestClient(apiURL){ Authenticator = new MyAuthenticator(resp_URL, username, pw)};
client.CookieContainer = new CookieContainer();
var logonRequest = new RestRequest(apiURL, Method.POST);
logonRequest
.AddParameter("username", username, ParameterType.GetOrPost)
.AddParameter("password", pw , ParameterType.GetOrPost);
// This fails. The response is 404. Looking back at the logonRequest resource, it is now the apiURL:
response = client.Execute(logonRequest);
成功登录后,将使用cookie中的会话身份验证凭据将预期结果重定向回API URL。