使用 WebRequest.ContentLength

Using WebRequest.ContentLength

string name = textBox.Text;
string favColour = textBox1.Text;

ASCIIEncoding encoding = new ASCIIEncoding();

string postData = "name=" + name + "&favColour" + favColour;
byte[] data = encoding.GetBytes(postData);
WebRequest request = WebRequest.Create("mywebsite.com");

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

Stream stream = request.Get;

Visual Studio 2015 has a problem with request.ContentLength.It 表示WebRequest中没有ContentLength的定义。

您可以尝试投射到 HttpWebRequest:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("mywebsite.com");

通常不需要手动设置 ContentLength 属性,因为它会在您写入请求流时自动完成。