我一直在尝试登录到服务器,以获取身份验证cookie(会话cookie),然后我可以将其用于进一步对服务器的调用。我看过的每个示例都遵循相同的模式:
HttpWebRequest request = WebRequest.Create(loginURL) as HttpWebRequest;
var response = request.GetResponse() as HttpWebResponse;
var cookies = response.Cookies;
这对我没有用,因为cookies变量最终为空,并且调试分析显示response.Cookies为空。服务器归我所有,通过调试,我可以看到cookie已被设置。如果我使用Firefox登录到我的网站,则也可以看到cookie。所以我知道cookie已被设置。
经过一些折腾之后,我发现cookie是在请求中设置的,而不是响应中设置的。因此下面的代码有效。我的问题是:为什么?为什么请求被填充,而不是响应?这与post有关吗,而不是get?我完全困惑了。
private void Login()
{
string userName = UserNameText.Text;
string password = PasswordText.Password;
string baseURL = URLText.Text;
string loginURL = baseURL + "/Authentication/LoginAction";
HttpWebRequest request = WebRequest.Create(loginURL) as HttpWebRequest;
request.Method = "POST";
string formContent =
"UserName=" + userName +
"&Password=" + password;
var byteArray = Encoding.UTF8.GetBytes(formContent);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
request.CookieContainer = new CookieContainer();
try
{
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (var response = request.GetResponse() as HttpWebResponse)
{
var cookies = request.CookieContainer;
if (cookies.Count != 0)
{
cookies_ = cookies;
}
}
}
}
catch(Exception ex)
{
// don't bother too much
Debug.WriteLine(ex.Message);
}
}