通过 HttpWebRequest 使用 HTTP POST 时执行表单重定向
我们最初通过表单提交登录凭据。现在,我们尝试使用 C# 使用 HttpWebRequest
通过 HTTP POST 以编程方式提交相同的登录凭据,从而模仿相同的行为。
我们知道我们正在正确发送数据,并且 Web 服务正在顺利接收和验证登录数据。
但问题是,当我们使用表单登录时,Web 服务会在成功时自动重定向用户。当使用 HttpWebRequest 时,我们似乎无法以某种方式重复这一点,因为用户和请求存在于两个不同的会话中(我认为)。
使用时成功身份验证时应如何执行重定向行为 HttpWebRequest
? 当我们手动重定向时,我们会被视为没有重定向已验证。
为了便于说明,我的请求代码类似于以下内容:
// var data = some byte[] data
var request =
(HttpWebRequest)WebRequest.Create("http://domain.com/login.asp");
request.ContentType = "x-www-form-urlencoded";
request.ContentLength = data.Length;
request.Method = "POST";
using (var stream = request.GetRequestStream()) {
stream.Write(data, 0, data.Length);
stream.Close();
}
var response = (HttpWebResponse)request.GetResponse();
我将其布置为 ASP.NET MVC 3 项目,因此此代码或多或少出现在控制器操作中。
We were initially submitting login credentials via a form. Now we're trying to mimic the same behavior by using C# to programmatically submit the same login creds via HTTP POST using HttpWebRequest
.
We know that we're sending in the data correctly, and that the web service is receiving and authenticating the login data smoothly.
The problem, however, is that when we're using the form for login, the web service automatically redirects the user on success. We can't seem to duplicate that somehow when using an HttpWebRequest
because the user and the request exist on two different sessions (I think).
How should I perform the redirect behavior on successful authentication when using HttpWebRequest
? When we redirect manually, we're treated as if we're not authenticated.
For point of illustration, my request code looks similar to the following:
// var data = some byte[] data
var request =
(HttpWebRequest)WebRequest.Create("http://domain.com/login.asp");
request.ContentType = "x-www-form-urlencoded";
request.ContentLength = data.Length;
request.Method = "POST";
using (var stream = request.GetRequestStream()) {
stream.Write(data, 0, data.Length);
stream.Close();
}
var response = (HttpWebResponse)request.GetResponse();
I'm laying this out as an ASP.NET MVC 3 project, so this code more or less appears in a controller action.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论