如何将数据从WPF应用程序发送到MVC3控制器操作方法?

时间:2012-04-19 23:41:47

标签: c# asp.net-mvc-3 rest .net-4.0

这是我在客户端WPF端运行的代码:

string path = @"C:\Users\Sergio\Desktop\test3.log";

// A List<DataObj>
var parsedData = LogParser.Parse(path); 

我想将这个复杂的对象发送到我的Web应用程序(MVC3)上的Action方法,并用它做一些事情。请注意,这是一个完全独立的项目。

这是我创建的ActionMethod:

[HttpPost]
public class MicroOracleController : Controller
{
    public ActionResult UploadData(List<DataObj> matches)
    {
        //Do something here.

        return RedirectToAction("Index", "Home");
    }
}

在客户端,如何调用此ActionMethod?

我试过了:

private void Button_Click(object sender, RoutedEventArgs e)
{
    string path = @"C:\Users\Sergio\Desktop\test3.log";
    var parsedMatches = LogParser.Parse(path);

    // Create a request using a URL that can receive a post. 
    WebRequest request = WebRequest.Create("http://localhost:35082/MicroOracle/UploadData/");
    // Set the Method property of the request to POST.
    request.Method = "POST";
    // Create POST data and convert it to a byte array.
    byte[] byteArray = Encoding.UTF8.GetBytes(parsedMatches); //I can't do this with a complex object.
    // 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.
    Console.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.
    Console.WriteLine(responseFromServer);
    // Clean up the streams.
    reader.Close();
    dataStream.Close();
    response.Close();
}

但我不能GetBytes复杂的对象。

0 个答案:

没有答案