Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've got an MVC5 Web Api web application that I'm trying to send sensor data to.

My controller;

C#
[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;

JavaScript
var request = require('request-promise')
var exp = require('express')

var app = exp();

const opts = {
  method: 'GET',
  url: 'http://www.jaxcoder.com/api/Sensor/getAll'
}
//This call works fine
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://jaxcoder.com/api/Sensor/addRow',
  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;

C#
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.
Posted
Updated 2-Jul-18 2:29am
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900