将数据从ASPX发布到ASP页时删除空格,但在发布到ASPX页时保留空格

时间:2014-04-15 21:32:01

标签: c# asp.net asp-classic urlencode webrequest

将数据从ASPX发布到ASP页面时删除空格,但在将数据发布到ASPX页面时保留空格。以下是示例代码

  

调用程序代码(后面的aspx代码)

WebRequest request = WebRequest.Create("http://localhost/asppost/asppost.asp");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "LastName=Ahamed&Addr1=100 Main Street";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Debug.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Debug.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
  

asppost.asp

<%
Dim Lname, AddressLine1
Lname = Request.Form("LastName")
AddressLine1 = Request.Form("AddressLine1")
Response.Write("Last Name: " & Lname)
Response.Write(" Address Line1: " & AddressLine1)
%>
  

输出

OK
Last Name: Ahamed Address Line1: 100MainStreet

如果我使用HttpUtility.UrlEncode,问题将解决,但我的问题是为什么以及如何在将相同数据(没有UrlEncode)发布到ASPX页面时保留空格?

string postData = "LastName=" + HttpUtility.UrlEncode("Ahamed") + "&AddressLine1=" + HttpUtility.UrlEncode("100 Main Street");

请分享您的想法。

1 个答案:

答案 0 :(得分:0)

postData字符串中的数据需要是URL编码。

postData = "LastName=Ahamed&Addr1=100 Main Street";

需要:postData = "LastName=Ahamed&Addr1=100+Main+Street";

在代码中,这将是:

string postData = "LastName=" + HttpUtility.UrlEncode(lastName);
postData += "&Addr1=" + HttpUtility.UrlEncode(addr1);