2013-10-10 28 views
1

我使用c#console應用程序發送數據到本地網站。發送數據的功能是:如何從c#接收asp網站上的數據?

public static HttpWebRequest GetRequest(String url, NameValueCollection nameValueCollection) 
    { 
     // Here we convert the nameValueCollection to POST data. 
     // This will only work if nameValueCollection contains some items. 
     var parameters = new StringBuilder(); 

     foreach (string key in nameValueCollection.Keys) 
     { 
      parameters.AppendFormat("{0}={1}&", 
       HttpUtility.UrlEncode(key), 
       HttpUtility.UrlEncode(nameValueCollection[key])); 
     } 

     parameters.Length -= 1; 

     // Here we create the request and write the POST data to it. 
     var request = (HttpWebRequest)HttpWebRequest.Create(url); 
     request.Method = "POST"; 

     using (var writer = new StreamWriter(request.GetRequestStream())) 
     { 
      writer.Write(parameters.ToString()); 
     } 

     return request; 
    } 

url和NameValueCollection都是正確的。 但我不能在網站上收到任何東西。 網站代碼是:

System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Current.Request.InputStream); 

    string requestFromPost = reader.ReadToEnd(); 
    Response.Write(requestFromPost); 

我是新來的asp.net。我錯過了什麼?

回答

1

試試這個。

var parameters = new StringBuilder(); 

foreach (string key in nameValueCollection.Keys) 
{ 
    parameters.AppendFormat("{0}={1}&", 
     HttpUtility.UrlEncode(key), 
     HttpUtility.UrlEncode(nameValueCollection[key])); 
} 

parameters.Length -= 1; 

var request = (HttpWebRequest)WebRequest.Create(url); 
request.Method = "POST"; 
request.ContentType = "application/x-www-form-urlencoded"; 

// Every so often I've seen weird issues if the user agent isn't set 
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; 

// encode the data for transmission 
byte[] bytedata = Encoding.UTF8.GetBytes(parameters.ToString()); 

// tell the other side how much data is coming 
request.ContentLength = bytedata.Length; 

using (Stream writer = request.GetRequestStream()) 
{ 
    writer.Write(bytedata, 0, bytedata.Length); 
} 
String result = String.Empty; 

using (var response = (HttpWebResponse)request.GetResponse()) { 
    using(StreamReader reader = new StreamReader(response.GetResponseStream())) { 
     result = reader.ReadToEnd(); // gets the response from the server 
     // output this or at least look at it. 
     // generally you want to send a success or failure message back. 
    } 
} 

// not sure why you were returning the request object. 
// you really just want to pass the result back from your method 
return result; 

您可能想要將上述大部分內容包裝在try..catch中。如果帖子失敗,那麼它會拋出異常。


在接收端,它更容易一點。您可以執行以下操作:

String val = Request.QueryString["myparam"]; 

或者只是遍歷查詢字符串集合。

+0

錯誤:參數不當前上下文 錯誤存在:不能轉換的byte []到char [] – SparkWerk

+0

@SparkWerk:我以爲你還是要建立自己的參數...更新 – NotMe

+0

即時得到的想法。但如何將byte []轉換爲char []錯誤:無法將byte []轉換爲char []? – SparkWerk

相關問題