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

后端 未结 2 1108
一生所求
一生所求 2021-01-02 03:39

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

相关标签:
2条回答
  • 2021-01-02 03:53

    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

    0 讨论(0)
  • 2021-01-02 03:58

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

    var result = client.UploadString(_webapiUrl, "POST", "=hello"); // NOTE '='
    
    0 讨论(0)
提交回复
热议问题