我肯定想念一些很明显的东西,但是我不知道是什么。我有一个DoLoginAsync
像这样:
private async Task DoLoginAsync(bool force = false)
{
try
{
if (client.Cookies.ContainsKey("user_credentials") && !force)
{
return;
}
var html = client.Request("login").GetStringAsync().Result;
var doc = new HtmlDocument();
doc.LoadHtml(html);
var csrf_token = doc.DocumentNode.SelectNodes("//meta[@name='csrf-token']").First().GetAttributeValue("content", string.Empty);
var values = new Dictionary<string, string>
{
{ "user_session[email]", user },
{ "user_session[password]", password },
{ "authenticity_token", csrf_token }
};
var result = await client.Request("user_session").PostUrlEncodedAsync(values);
}
catch (Exception e)
{
}
当我在具有catch子句中的断点的测试中运行此代码时,会出现异常
Call failed with status code 404 (Not Found): GET http://www.whatever.com/user_session
WTF?我期望PostUrlEncodedAsync
执行POST,而不是GET。有人知道为什么会发生这种情况吗?
Flurl客户端实例化为client = new FlurlClient(BASE_URL).EnableCookies();
更新
尝试了以下测试,但由于相同的异常而失败
[TestMethod]
public async Task TheTest()
{
var message = "";
try
{
var client = new FlurlClient("http://www.slimmemeterportal.nl/").EnableCookies();
var html = await client.Request("login").GetStringAsync();
var doc = new HtmlDocument();
doc.LoadHtml(html);
var csrf_token = doc.DocumentNode.SelectNodes("//meta[@name='csrf-token']").First().GetAttributeValue("content", string.Empty);
var values = new Dictionary<string, string>
{
{ "user_session[email]", "******" },
{ "user_session[password]", "******" },
{ "commit", "inloggen" }, // Not sure if this is actually needed, but it is in the website's request parameters.
{ "authenticity_token", csrf_token }
};
var result = await client.Request("user_session").PostUrlEncodedAsync(values);
}
catch (FlurlHttpException ex)
{
message = ex.Message;
}
Assert.AreEqual("Call failed with status code 404 (Not Found): POST http://www.slimmemeterportal.nl/user_session", message);
}
答案 0 :(得分:2)
神秘的问题解决了:事实证明,在使用Wireshark进行一些调试之后,网站返回了HTTP状态代码301。如here所述,默认操作是使用GET在响应的位置标头中跟踪URI,即使原始请求是POST。