我从WebResponse
获得HTTPWebRequest
时被困在这里。
WebRequest.GetResponse()
方法抛出WebException
("500 Internal Server Error")
。当我阅读返回的HTML时,它说:
HTTP 403:禁止(POST中缺少'_xsrf'参数)
任何人都知道这个错误或者知道我做错了什么?
(我试图使用POST登录网站)
修改 我的源代码:
private String GetLoginCookies(String pHTTPurl, String pUserIDwithFormID, String pPasswordWithFormID)
{
String loginPageUrl = pHTTPurl;
CookieContainer cookieContainer = new CookieContainer();
var Request = (HttpWebRequest)WebRequest.Create(loginPageUrl);
Request.CookieContainer = cookieContainer;
Request.Method = "GET";
WebResponse Response = Request.GetResponse();
HttpWebResponse HttpResponse = Response as HttpWebResponse;
CookieCollection cookies = null;
if (HttpResponse != null)
{
//Cookies die benötigt werden um den Loginvorgang abzuschließen
cookies = HttpResponse.Cookies;
}
string formParams = string.Format(pUserIDwithFormID + "&" + pPasswordWithFormID);
Request = (HttpWebRequest)WebRequest.Create(loginPageUrl);
Request.CookieContainer = cookieContainer;
Request.UserAgent = "I am not a Bot! Ok maybe..";
WebResponse resp = null;
Request.ContentType = "application/x-www-form-urlencoded";
Request.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
Request.ContentLength = bytes.Length;
using (Stream os = Request.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
try
{
resp = Request.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
String TestResponse = sr.ReadToEnd();
}
}
catch (WebException WE)
{
DebugConsole.AppendText("HTTP Error:" + WE.Message + Environment.NewLine);
String HTML = new StreamReader(WE.Response.GetResponseStream()).ReadToEnd();
DebugConsole.AppendText(HTML);
return null;
}
String cookieHeader = resp.Headers["Set-cookie"];
if (String.IsNullOrEmpty(cookieHeader))
return null;
else
return cookieHeader;
}
答案 0 :(得分:2)
这实际上是因为web方法需要反csrf(跨站点请求伪造,此处有更多信息:https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF))验证参数。您可以做的是将csrf值附加到请求标头:
postHeaders.Add("X-CSRFToken", CSRF);
如果你需要任何帮助,也许你可以在这里粘贴你的源代码,所以我们可以照顾它
答案 1 :(得分:0)
OK!找到解决方案!
收到登录网站的回复后,在"Set-cookie"
标题中搜索_xsrf
。这是您必须在下一个POST
请求的标头中添加的令牌。