Search code examples
c#asp.net-corehttpclient

Calling HttpPost with a single string parameter not working


I have the following .Net Core 2.2 controller method, which is always receiving a null value:

public class ValuesController : Controller
{
    [HttpPost]
    public async Task<IActionResult> AddValue(string value)
    {
        var newValue = await DoSomethingWithValue(value); // value is null here
        // Other code
        return Ok();           
    }
}

The calling code is as follows:

string newValue = Guid.NewGuid();
//var stringContent = new StringContent(newValue);
var result = await httpClient.PostAsync(uri + newValue, null);
if (!result.IsSuccessStatusCode)

The controller method is called successfully, but whether I try to pass the value as HttpContent, or as a query parameter (e.g. myuri/AddValue/123) it still comes through as null. What could I be doing wrong here?


Solution

  • First, that's not a query param; that's a route segment. If you want to receive it that way, you need to specify a route param:

    [HttpPost("AddValue/{value}")]
    

    Otherwise, you need to send it as an actual query param, i.e. myuri/AddValue?value=123.

    As for the post, the default binding is FromForm, which is expecting an x-www-form-urlencoded or multipart/form-data encoded body, which is not what you're sending. You would need to do:

    var stringContent = new StringContent($"value={newValue}", Encoding.UTF8, "application/x-www-form-urlencoded");
    

    Or you can actually use FormUrlEncodedContent:

    var values = new Dictionary<string, string>
    {
        ["value"] = Guid.NewGuid().ToString()
    };
    var formUrlEncodedContent = new FormUrlEncodedContent(values);