Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST a string to Web API controller in ASP.NET 4.5 and VS 2012 RC

I am new to WebAPI and trying to learn it. I have an WebAPI controller to which I am trying to POST a string using WebClient from my Unit Test.

I am posting a string to my WebAPI using following code below.

using (var client = new WebClient())
{
   client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
   var result = client.UploadString(_webapiUrl, "POST", "hello");
}

Here is my controller.

[HttpPost]
public byte[] Post(string value)
{
   // Do something with value
}

I can hit a break point on my controller, but it doesn't seem to POST any string and I always get NULL value. What should I do to get the value ?

Thanks

like image 740
durbhakula Avatar asked Jul 26 '12 03:07

durbhakula


2 Answers

If all you need to receive is one value, use = before the value:

var result = client.UploadString(_webapiUrl, "POST", "=hello"); // NOTE '='
like image 104
Aliostad Avatar answered Nov 10 '22 05:11

Aliostad


Notice the key value pair that is formed for posting the values back to server. The Key should be same as you expect in action method parameter. In this case your Key is "VALUE"

[HttpPost]
public byte[] Post(string value)

Use the following code to post the value.

string URI = "http://www.someurl.com/controller/action";
string myParamters = "value=durbhakula";

using (WebClient wc = new WebClient())
{
    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    string HtmlResult = wc.UploadString(URI, myParameters);
}

UPDATE

I thank Aliostad for pointing my mistake. The parameter name should be empty while posting the form data in Web API.

string myParamters = "=durbhakula";

Also you need to put [FormBody] attribute in your action method. The FromBody attribute tells Web API to read the value from the request body

[HttpPost]
[ActionName("Simple")]
public HttpResponseMessage PostSimple([FromBody] string value)
{
..
..
}

Please see this link

like image 32
Anand Avatar answered Nov 10 '22 03:11

Anand