GET and POST to ASP.NET MVC via C#
本文关键字:MVC via NET ASP and POST to GET | 更新日期: 2023-09-27 18:32:04
我有一个用C#编写的Windows应用程序。此应用将部署到我的用户的桌面。它将与已创建的后端进行交互。后端是用 MVC 3 编写 ASP.NET。它公开了许多 GET 和 POST 操作,如下所示:
[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
}
我团队中的 Web 开发人员正在通过 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 操作?有人可以给我一些帮助吗?谢谢!
一种方法是将输入写入请求流。您需要将输入序列化为字节数组 请参阅下面的示例代码
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();
}
}
好吧,对于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);
你试过这个吗?