通过 HttpWebRequest 从远程域获取 cookie
我必须访问不同域上的页面: http://domain1/page1.aspx 和 http://domain2/page2.aspx (实际上它是http处理程序)。 通过 WebHttpRequest,我将 post 请求从 page1 发送到 page2。
string result;
var webRequest = (HttpWebRequest)WebRequest.Create("http://domain2/page2.aspx");
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = 0;
using (var webResponse = webRequest.GetResponse())
{
if (webResponse == null)
return null;
var reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8, true);
try
{
result = reader.ReadToEnd();
if (string.IsNullOrEmpty(result))
return null;
}
finally
{
reader.Close();
}
}
return result.Deserialize();
我知道,domain2 上有一个 cookie,但是当我进入 page2.aspx 时,cookie 集合是空的。 当我制作简单的 Response.Redirect 到 page2 时,cookie 存在。 那么是否可以提出这样的要求以及我在哪里出错了?或者也许还有另一种方法可以做这样的事情?
I have to pages on different domains: http://domain1/page1.aspx and http://domain2/page2.aspx (in real it's http handler).
By WebHttpRequest I'm sending post request from page1 to page2.
string result;
var webRequest = (HttpWebRequest)WebRequest.Create("http://domain2/page2.aspx");
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = 0;
using (var webResponse = webRequest.GetResponse())
{
if (webResponse == null)
return null;
var reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8, true);
try
{
result = reader.ReadToEnd();
if (string.IsNullOrEmpty(result))
return null;
}
finally
{
reader.Close();
}
}
return result.Deserialize();
I know, that there is a cookie on domain2, but when I'm getting in page2.aspx cookies collection is empty.
When I'm making simple Response.Redirect to page2, cookie exists.
So is it possible to make such requests and where I did mistake? Or maybe there is another method to do something like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在通过代码而不是通过浏览器向第 2 页发出请求。通常,它是一个将 cookie(与站点关联)发送到 Web 服务器的浏览器。在您的情况下,您需要在代码中从 page1 的响应手动传输 cookie 名称值到 page2 的请求(假设这就是您想要/意味着的)。
此外,默认情况下
HttpWebRequest
中禁用 cookie,因此即使 page2 服务器代码添加了一些 cookie,它也不会在响应对象中看到,除非您使用 CookiContainer 属性(阅读链接中的文档/示例)。You are doing the request to page 2 via code and not via browser. Typically its a browser that sends cookie (associated with site) to web servers. In your case, you need to transfer cookie name-values manually in code from page1's response to page2's request (assuming thats what you want/mean).
Further, cookies are disabled by default in
HttpWebRequest
, so even if page2 server code is adding some cookie, it won't be seen in response object unless you enable them using CookiContainer property (read the documentation/example in the link).