Myles McDonnell
Myles McDonnell

Reputation: 13335

null string parameter in body of POST request to WebAPI2 service

I have an action defined in a WebAPI2 controller as follows:

    [HttpPost]
    [Route("DataImport/Product/")]
    public DataImportJournalEntry ImportData([FromBody] string base64)
    {
        return _dataImportService.Import(Convert.FromBase64String(base64));
    }

and I'm building a request, using RestSharp, as follows:

    var base64 = {4Kb xml file loaded and encoded to base64}

    var client = new RestClient(Config.BaseAddress);

    var request = new RestRequest("DataImport/Product/", Method.POST);
    request.AddParameter("base64", base64, ParameterType.GetOrPost);
    request.AddHeader("accepts", "application/json");

    var response = client.Execute<DataImportJournalEntry>(request);

The routing is correct as the action is called but the base64 parameter is null on the server side?

Upvotes: 1

Views: 1056

Answers (1)

Myles McDonnell
Myles McDonnell

Reputation: 13335

Found it..when using the FromBody attribute there can be only one parameter in the body and WebAPI is looking for it as ={value} not as you would expect {key}={value}. So I simply passed the parameter name as an empty string in the test:

...
var request = new RestRequest("DataImport/Product/", Method.POST);
request.AddParameter("", base64);
...

More details here: http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

Upvotes: 2

Related Questions