2012-04-23 31 views
3

我有用C#编写的Windows应用程序。这个应用程序将被部署到我的用户的桌面。它将与已经创建的后端进行交互。后端是写在ASP.NET MVC 3,它包含了许多GET和POST操作如下所示:通过C#获取并发布到ASP.NET MVC

[AcceptVerbs(HttpVerbs.Get)] 
public ActionResult GetItem(string id, string caller) 
{ 
    // Do stuff 
} 

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult SaveItem(string p1, string p2, string p3) 
{ 
    // Do stuff 
} 

我们小组中的网页开发者成功地通过JQuery这些操作交互。所以我知道他们工作。但我需要弄清楚如何从我的Windows C#应用程序与它们进行交互。我正在使用WebClient,但遇到了一些性能问题,因此我被咨询使用WebRequest对象。在诚实地努力尝试这个,我试过如下:

WebRequest request = HttpWebRequest.Create("http://www.myapp.com/actions/AddItem"); 
request.Method = "POST"; 
request.ContentType = "application/x-www-form-urlencoded"; 
request.BeginGetResponse(new AsyncCallback(AddItem_Completed), request); 

我的问题是,我不知道如何真正的数据(参数值)送回到我的终点。如何将参数值发送回我的GET和POST操作?有人能给我一些帮助吗?谢谢!

回答

1

那么,与WebClient最简单的例子是这样的:

NameValueCollection postData = new NameValueCollection(); 
postData["field-name-one"] = "value-one"; 
postData["field-name-two"] = "value-two"; 

WebClient client = new WebClient(); 
byte[] responsedata = webClient.UploadValues("http://example.com/postform", "POST", postData); 

你试过吗?

+0

我无法使用WebClient。说来话长。但我真的需要使用WebRequest。 – 2012-04-23 17:24:29

4

一种方法是将输入写入请求流。您需要将输入序列化为字节数组 请参阅下面的示例代码

 string requestXml = "someinputxml"; 
     byte[] bytes = Encoding.UTF8.GetBytes(requestXml); 

     var request = (HttpWebRequest)WebRequest.Create(url); 
     request.Method = "POST"; 
     request.ContentLength = bytes.Length; 
     request.ContentType = "application/xml"; 

     using (var requestStream = request.GetRequestStream()) 
     { 
      requestStream.Write(bytes, 0, bytes.Length); 
     } 

     using (var response = (HttpWebResponse)request.GetResponse()) 
     { 
      statusCode = response.StatusCode; 

      if (statusCode == HttpStatusCode.OK) 
      {     
       responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); 
      } 
     } 
+0

也许我很困惑。但我知道我的web开发人员正在通过jQuery将json提交回我的操作。我如何通过WebRequest提交相同类型的信息? – 2012-04-23 17:26:57

+0

您需要将数据序列化为JSON字符串。看看使用JSON.net。然后,您将该字符串转换为一个字节数组,类似于testuser对其变量“requestXml”所做的操作。 – villecoder 2012-04-23 17:46:29