Search code examples
c#webclientasp.net-apicontrolleruploadstring

string parameter in controller is null when using webclient


When I use WebClient to call a function in a controller

using (WebClient client = new WebClient())
{
    client.BaseAddress = "http://localhost/";
    client.Headers.Add("Content-Type", "application/json");
    client.UploadString("api/test", HttpMethod.Put.ToString(), stringParameter);
}

I called the function in controller successfully but the "stringParameter" in controller is empty like the following code:

[Route("api/test")]
[HttpPut]
public async Task<IHttpActionResult> Test([FromBody] string stringParameter)
{
    if (!ModelState.IsValid)
    {
        // the flow goes here
        return BadRequest(ModelState);
    }
    // ...
}

I would like to know where is the mistake(s) I made and how to fix the problem(s). Thank you very much.

Remark: "stringParameter" is fine if it is numeric such as "123" but not work if it is "A123" or "B123".


Solution

  • As you're setting content type to "application/json" you should be sending a valid JSON value rather then raw string. A number is JSON and in plain text is the same, so that's why it works.

    Try serializing the text to JSON before sending: JsonConvert.ToString(stringParameter); (I'm using Newtonsoft.Json nuget package here)

    Alternatively you can try to use content type text/plain, but I'm not sure if your web api is configured to handle that by default.