WebRequest MVC HttpPost DateTime Format - PullRequest
       6

WebRequest MVC HttpPost DateTime Format

1 голос
/ 19 января 2011

У меня есть MVC-действие .....

[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

Ответы [ 3 ]

4 голосов
/ 19 января 2011

Прежде всего параметр 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 в действии вашего контроллера, поэтому вы должны отправить именно это имя параметра.

1 голос
/ 19 января 2011

Я думаю, что ваша строка postData неверна.Оно должно быть:

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

Дополнительная информация: привязка параметров ASP.NET MVC к аргументам в действии контроллера будет совпадать с именем отправленных значений или строкой запроса.

0 голосов
/ 19 января 2011

Вы ошиблись? Вы публикуете «myDate», но ваш метод действия ожидает «myDateTime».

...