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
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
If all you need to receive is one value, use =
before the value:
var result = client.UploadString(_webapiUrl, "POST", "=hello"); // NOTE '='