I've got an MVC5 Web Api web application that I'm trying to send sensor data to.
My controller;
[HttpGet]
[Route("api/Sensor/GetByTopic")]
public IHttpActionResult GetByTopic(string name)
{
string url = "getByTopic/" + name;
List<SensorData> svn = GetData(url);
return Ok(svn);
}
[AcceptVerbs("POST", "GET")]
[HttpPost]
[Route("api/Sensor/addRow")]
public IHttpActionResult addRow([FromBody]string data)
{
TagCollectionRepository.AddTag(data);
return Ok();
}
and on the Pi i have a very basic Node.JS application to get and post data. The GET works fine but the POST is giving me problems. The controller receives the request but the data parameter is always null so I'm thinking that I'm sending the body data wrong in the Pi app.
The Pi code;
var request = require('request-promise')
var exp = require('express')
var app = exp();
const opts = {
method: 'GET',
url: 'http://www.jaxcoder.com/api/Sensor/getAll'
}
request(opts){
.then(function(res) {
console.log('res);
})
.catch(function(err) {
console.log('err: ', err);
});
const options = {
headers: { 'content-type' : 'application/x-www-form-urlencoded' },
method: 'POST',
url: 'http:
form: {
data: 'From Pi'
}
}
request(options)
.than(function(res) {
console.log('resp: ', res);
})
.catch(function(err) {
console.log('err: ', err);
});
app.get('/', (req, res) => res.send('hello'));
app.listen(3000);
[update]
When I created the addRow method I just stuck a string parameter to see if I could communicate from the Pi to my Web Api service. Well it turns out that in Web Api complex values are easy but capturing raw request body data is not.
So the solution was to add a view model class;
public class StringViewModel {
public string data { get; set; }
}
then change the addRow method to reflect changes.
I found the answer in a post by Rick Strahl
Accepting Raw Request Body Content with ASP.NET Web API
[
^]
[/update]
What I have tried:
I've tried variation of options for the POST that I found googling such as using body instead of form with the "json: true o" option, leaving out the headers option but nothing worked and I'm stumpted.