首先,我用cookie容器创建了HttpClientHandler
CookieContainer cookies = new CookieContainer(); HttpClientHandler handler = new HttpClientHandler(); handler.CookieContainer = cookies; handler.UseCookies = true; var hc = new HttpClient(handler);
然后我点击Base Url只是为了获得带有“__RequestVerificationToken”的cookie
string r = await hc.GetStringAsync(BaseUrl);
HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair<string,string>("UserName","admin"),new KeyValuePair<string,string>("Password",password),}); HttpResponseMessage response = await hc.PostAsync(LoginUrl,content);
然后我得到服务器错误“所需的防伪表单字段”__RequestVerificationToken“不存在”.
但是当我在fiddler中检查请求时,我可以看到“__RequestVerificationToken”已经添加到请求的cookie中.
然后我尝试在IE中手动登录,并检查IE发送的请求类型.
然后我发现IE也在表单中放了“__RequestVerificationToken”,所以我在表单中添加了cookie
new KeyValuePair<string,string>("__RequestVerificationToken",cookies.GetCookies(new Uri(BaseUrl)).Cast<Cookie>().FirstOrDefault(x => x.Name == "__RequestVerificationToken").Value)
然后我收到了这个错误
“所提供的防伪令牌的验证失败.交换了cookie”_RequestVerificationToken“和表单字段”_RequestVerificationToken“.”
任何的想法?
谢谢