0

我正在尝试用 C# 编写一个命令,以便从服务器获取会话 cookie。

例如从命令行我正在执行下一行:

curl -i http://localhost:9999/session -H "Content-Type: application/json" -X POST -d '{"email": "user", "password": "1234"}'


HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Date: Thu, 03 Jan 2013 15:52:36 GMT
Content-Length: 30
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Set-Cookie: connect.sid=s%3AQqLLtFz%2FgnzPGCbljObyxKH9.U%2Fm1nVX%2BHdE1ZFo0zNK5hJalLylIBh%2FoQ1igUycAQAE; Path=/; HttpOnly

现在我正在尝试在 C# 中创建相同的请求

string session = "session/";
string server_url = "http://15.185.117.39:3000/";
string email = "user";
string pass = "1234";
string urlToUSe = string.Format("{0}{1}", server_url, session);

HttpWebRequest httpWebR = (HttpWebRequest)WebRequest.Create(urlToUSe);
httpWebR.Method = "POST";
httpWebR.Credentials = new NetworkCredential(user, pass);
httpWebR.ContentType = "application/json";

HttpWebResponse response;
response = (HttpWebResponse)httpWebR.GetResponse();

但是当我运行这段代码时,我在最后一行得到了 401 错误。

什么地方出了错 ?

谢谢 !

4

1 回答 1

1

什么地方出了错 ?

你在Fiddler中看不到吗?您提供的NetworkCredential与使用电子邮件地址和用户名发布 JSON 字符串不同,它:

为基于密码的身份验证方案提供凭据,例如基本、摘要、NTLM 和 Kerberos 身份验证。.

您需要使用 HttpWebRequest 发布数据。如何执行此操作在如何:使用 WebRequest 类发送数据中进行了描述:

string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);

request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;

Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

您当然可以在需要的地方替换适当的值。

此外,您可以使用WebClient更容易发布数据的类。默认情况下它不支持 cookie,但我写了一篇关于如何为WebClient.

于 2013-01-03T16:15:19.080 回答