JavaScript Developer
JavaScript Developer

Reputation: 4008

GET and POST to ASP.NET MVC via C#

I have a Windows app written in C#. This app will be deployed to my user's desktops. It will interact with a back-end that has already been created. The back-end is written in ASP.NET MVC 3. It exposes a number of GET and POST operations as shown here:

[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
}

The web developers on my team are successfully interacting with these operations via JQuery. So I know they work. But I need to figure out how to interact with them from my Windows C# app. I was using the WebClient, but ran into some performance problems so I was consulted to use the WebRequest object. In an honest effort to attempt this, I tried the following:

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); 

My problem is, I'm not sure how to actually send the data (the parameter values) back to my endpoints. How do I send the parameter values back to my GET and POST operations? Can someone give me some help? Thank you!

Upvotes: 3

Views: 3206

Answers (2)

testuser
testuser

Reputation: 678

One way is to write the input to request stream. You need to serialize input to byte array Please see below sample code

        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();
            }
        }

Upvotes: 4

kprobst
kprobst

Reputation: 16651

Well, with WebClient the simplest example would be something like this:

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);

Have you tried this?

Upvotes: 1

Related Questions