forms-authentication – 如何使用Windows Store App中的HttpClient登录ASP.Net MVC网站(表单身份验证)?

前端之家收集整理的这篇文章主要介绍了forms-authentication – 如何使用Windows Store App中的HttpClient登录ASP.Net MVC网站(表单身份验证)?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
首先,我用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);

然后我将用户名/密码发布到登录URL

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“.”

然后我无法在谷歌上获得此错误的任何搜索结果.

任何的想法?

谢谢

解决方法

发现了这个问题.

添加到cookie的“__RequestVerificationToken”与添加到表单的“_RequestVerificationToken”不同.

所以我从返回的Html字符串中获取了表单中“__RequestVerificationToken”的值,然后就可以了!

猜你在找的Windows相关文章