Cookies not set with RestSharp in Windows Phone 7 app
今天,我尝试登录包含身份验证表单的页面。
我在Windows Phone 7上使用RestSharp,我几乎尝试了所有操作,但没有成功。
在台式计算机上的浏览器中,当我使用登录页面(http://myanimelist.net/login.php)并输入有效的凭据时,我将被重定向到面板页面(http://myanimelist.net) /panel.php)
在Windows Phone 7(和8)上,当我尝试使用RestSharp进行身份验证时,我被重定向到面板页面,但出现以下错误:
Error: You must first login to see this page.
实际上,我没有经过身份验证,也无权查看面板页面。
我在WPF应用程序中尝试了同样的事情,并且在那里工作了。
在我的WPF应用中,我有以下代码:
1 2 3 4 5 6 7 8 9 10 11 | var client = new RestSharp.RestClient(); client.BaseUrl ="http://myanimelist.net/login.php"; client.Authenticator = new SimpleAuthenticator("username","mylogin","password","mypassword"); client.CookieContainer = new CookieContainer(); var request = new RestRequest(Method.POST); var response = client.Execute(request); |
属性" response.Content"将包含带有一些信息的页面和带有我的登录名的欢迎消息。这表示我已通过身份验证。
但...
使用Windows Phone 7中的以下代码,属性" response.Content"将包含一个包含一些信息和以下消息的页面:
Error: You must first login to see this page
这是使用的WP7代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | var client = new RestSharp.RestClient(); client.BaseUrl ="http://myanimelist.net/login.php"; client.Authenticator = new SimpleAuthenticator("username","mylogin","password","mypassword"); client.CookieContainer = new CookieContainer(); var myRequest = new RestRequest(Method.POST); client.ExecuteAsync(myRequest, response => { var t = response.Content; }); |
我错过了什么? WP7上的RestSharp和WPF应用之间有区别吗?
我使用Fiddler来检查会发生什么,我可以看到cookie从未在WP7上设置过(在WPF应用程序中已设置cookie)。
编辑:
我发现一些有趣的事情,当我得到响应时,我可以在Fiddler中看到在WPF应用程序和WP7应用程序中设置了cookie。
因此,在提出请求之前,我尝试将Cookie添加到我的WP7应用程序中,并且它可以正常工作。
我添加了我在Fiddler中看到的值,但找不到用RestSharp检索这些值的方法。
这是我在执行请求之前尝试添加的内容:
1 2 | myRequest.AddParameter("A","theFirstValue", ParameterType.Cookie); myRequest.AddParameter("B","theSecondValue", ParameterType.Cookie); |
实际上,我找到了一种方法。
在响应中,我在标题(Set-cookie)中包含了cookie。 我从标题中提取cookie,并将其添加到需要cookie的下一个请求中。