![](/img/trans.png)
[英]Get echo value after post request C# (WebClient UploadValues)
[英]How to get Location header with WebClient after POST request
成功完成POST请求后,我需要使用WebClient
来获取响应标头中的url。
但是,执行WebClient.UploadValues
之后获得的标头是重定向后的来自页面的标头。
此代码模拟与使用WebClient
Browser中相同的操作:
NameValueCollection formData = new NameValueCollection();
formData["username"] = user;
formData["password"] = password;
byte[] responseBytes = webClient.UploadValues(loginUrl, "POST", formData);
string response = Encoding.UTF8.GetString(responseBytes);
string allheaders = "";
for (int i = 0; i < webClient.ResponseHeaders.Count; i++)
{
allheaders += Environment.NewLine + webClient.ResponseHeaders.GetKey(i) + " = " + webClient.ResponseHeaders.Get(i);
}
File.WriteAllText("headers_2.txt", "[HEADER_2] " + allheaders);
...给出的结果headers_2.txt不包含位置标题(这些标题来自用户重定向到的页面):
[HEADER_2]语法=无缓存Cache-Control =无存储,无缓存,必须重新验证日期=星期三,2018年2月14日10:58:10 GMT过期=星期四,1981年11月19日08:52:00 GMT P3P = fffff Set-Cookie = sid = ffffff; 路径= /,gameapi_console = 0; expires =星期六,2018年3月17日10:58:10 GMT; 最大年龄= 2678400; 路径= /,bptid = FFFFFF; 路径= /服务器= Apache Vary =接受编码,用户代理Access-Control-Allow-Origin = *内容类型= text / html; charset = UTF-8传输编码=分块
如何使用WebClient获取位置标头? 如果可以的话。
感谢您的评论。
我忘了展示我尝试过的东西。 因此,我创建了自己的类,该类继承自WebClient
。 我当时在想,如果我是在解雇UploadValuesCompleted
的那一刻读取标题的,那么在自动重定向之前,我将拥有标题。 不幸的是,由于未知原因,即使我确实调用webClient.UploadValues(loginUrl, "POST", formData)
也永远不会触发该事件。
class FAWebClient : WebClient
{
public event Action<string> OnLocationHeaderFound;
public FAWebClient(Action<string> pOnLocationHeaderFound = null) :base()
{
UploadValuesCompleted += OnUploadValuesCompleted;
if(pOnLocationHeaderFound != null)
this.OnLocationHeaderFound += pOnLocationHeaderFound;
}
protected override void OnUploadValuesCompleted(object sender, UploadValuesCompletedEventArgs e)
{
if (this.OnLocationHeaderFound != null)
{
for (int i = 0; i < this.ResponseHeaders.Count; i++)
{
System.Diagnostics.Debug.WriteLine(this.ResponseHeaders.GetKey(i) + " = " + this.ResponseHeaders.Get(i));
if (this.ResponseHeaders.GetKey(i).ToLower() == "location")
{
OnLocationHeaderFound(this.ResponseHeaders.Get(i));
}
}
}
base.OnUploadValuesCompleted(e);
}
}
还请注意,使用HttpClient
可以解决此问题,只需将itit HttpClient.AllowAutoRedirect
为false:
var handler = new HttpClientHandler()
{
AllowAutoRedirect = false
};
因此,我必须在应用程序逻辑中进行很多更改,但是它可以正常工作。 但是,如果有人提供解决方案或回答如何使用WebClient
实现该问题,我将保持开放状态。
因此,您似乎已经知道解决方案。
您只需要配置WebClient即可使用它。
假设您的服务器端代码如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication12.Controllers
{
public class HomeController : Controller
{
[HttpPost]
public ActionResult Login(LoginModel credential)
{
//code
Response.Headers.Add("IndexHeader","IndexHeaderValue");
return RedirectToAction("About");
}
public ActionResult About()
{
Response.Headers.Add("AboutHeader", "AboutHeaderValue");
return View();
}
}
public class LoginModel
{
public string username { get; set; }
public string password { get; set; }
}
}
您可以像这样创建自定义WebClient:
using System;
using System.Collections.Specialized;
using System.Net;
namespace ConsoleApp18
{
public class NoRedirectWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
var temp = base.GetWebRequest(address) as HttpWebRequest;
temp.AllowAutoRedirect = false;
return temp;
}
}
class Program
{
static void Main(string[] args)
{
MakeRequest(new WebClient());//Prints the AboutHeader
Console.WriteLine();
MakeRequest(new NoRedirectWebClient());//Prints the IndexHeader
Console.ReadLine();
}
private static void MakeRequest(WebClient webClient)
{
var loginUrl = @"http://localhost:50900/Home/Login";
NameValueCollection formData = new NameValueCollection();
formData["username"] = "batman";
formData["password"] = "1234";
webClient.UploadValues(loginUrl, "POST", formData);
string allheaders = "";
for (int i = 0; i < webClient.ResponseHeaders.Count; i++)
allheaders += Environment.NewLine + webClient.ResponseHeaders.GetKey(i) + " = " +
webClient.ResponseHeaders.Get(i);
Console.WriteLine("******"+webClient.GetType().FullName+"*******");
Console.Write(allheaders);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.