我要做一个重定向发送到另一个页面的变量值a和p.我不能使用GET方法,如:http://urlpage?a=1&p=2.我必须用post方法发送它们.如何在不使用c#表单的情况下发送它们?
小智 5
这个类包装了表单.有点hacky但它的确有效.只需将post值添加到类中并调用post方法即可.
public class RemotePost
{
private Dictionary<string, string> Inputs = new Dictionary<string, string>();
public string Url = "";
public string Method = "post";
public string FormName = "form1";
public StringBuilder strPostString;
public void Add(string name, string value)
{
Inputs.Add(name, value);
}
public void generatePostString()
{
strPostString = new StringBuilder();
strPostString.Append("<html><head>");
strPostString.Append("</head><body onload=\"document.form1.submit();\">");
strPostString.Append("<form name=\"form1\" method=\"post\" action=\"" + Url + "\" >");
foreach (KeyValuePair<string, string> oPar in Inputs)
strPostString.Append(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", oPar.Key, oPar.Value));
strPostString.Append("</form>");
strPostString.Append("</body></html>");
}
public void Post()
{
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Write(strPostString.ToString());
System.Web.HttpContext.Current.Response.End();
}
}
Run Code Online (Sandbox Code Playgroud)
使用WebClient.UploadStringorWebClient.UploadData可以轻松地将数据 POST 到服务器。I\xe2\x80\x99ll 显示使用 UploadData 的示例,因为 UploadString 的使用方式与 DownloadString 相同。
byte[] bret = client.UploadData("http://www.website.com/post.php", "POST",\n System.Text.Encoding.ASCII.GetBytes("field1=value1&field2=value2") );\n\nstring sret = System.Text.Encoding.ASCII.GetString(bret);\nRun Code Online (Sandbox Code Playgroud)\n\n更多: http: //www.daveamenta.com/2008-05/c-webclient-usage/
\n