2011-01-18 87 views
1

我有一個MVC行動.....WebRequest的MVC HttpPost日期時間格式

[HttpPost] 
public ActionResult DoStuff(string myString, DateTime myDateTime) 

...和我打電話從像這樣緊湊的框架應用程序的操作.....

WebRequest request = WebRequest.Create(url); 

     // Set the Method property of the request to POST. 
     request.Method = "POST"; 
     request.Proxy = null; 

     // Create POST data and convert it to a byte array. 
     string postData = "myString=Bonjour&myDateTime=" + DateTime.Now.ToString(); 

     byte[] byteArray = Encoding.UTF8.GetBytes(jsonPostData); 

     // 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. 
     using (Stream dataStream = request.GetRequestStream()) 
     { 
      dataStream.Write(byteArray, 0, byteArray.Length); 
     } 

     // Get the response. 
     using (WebResponse response = request.GetResponse()) 
     { 
      // Display the status. 
      // Console.WriteLine(((HttpWebResponse)response).StatusDescription); 

      // Get the stream containing content returned by the server. 
      using (Stream responseStream = response.GetResponseStream()) 
      { 
       // Read the response... 
       using (StreamReader reader = new StreamReader(responseStream)) 
       { 
        Console.WriteLine(reader.ReadToEnd()); 
       } 
      } 
     } 

問題是「myDateTime」參數始終爲空? postData字符串應該採用什麼格式才能工作(我已經嘗試了很多!)?

非常感謝,

ETFairfax

+0

問題是日期時間格式中的空格。換成%20,一切都很好。 – ETFairfax 2011-01-19 00:13:09

回答

4

首先DateTime參數不能爲空。這是一種值類型。其次大家都對這樣一個簡單的任務編寫太多代碼:

using (var client = new WebClient()) 
{ 
    var values = new NameValueCollection 
    { 
     { "myString", "Bonjour" }, 
     { "myDateTime", DateTime.Now.ToString("yyyy-MM-dd") }, 
    }; 
    byte[] result = client.UploadValues(url, values); 
    string strResult = Encoding.UTF8.GetString(result); 
} 

還要注意該參數在控制器的動作稱爲myDateTime,所以你必須把正是這個參數名稱。

+0

WebClient在Compact Framework上不可用,並且將null分配給DateTime的事實是問題! – ETFairfax 2011-01-19 00:07:17

1

我覺得你POSTDATA字符串是錯誤的。它應該是:

string postData = "myString=Bonjour&myDateTime=" + DateTime.Now.ToString(); 

更多信息:ASP.NET MVC的參數在控制器的行動結合參數匹配上公佈值的名稱,或在查詢字符串。

0

你拼錯了嗎?您正在發佈'myDate',但您的操作方法需要'myDateTime'。