2011-01-18 84 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'。