Home > OS >  How to pass JSON as parameter to Post method in controller .net api
How to pass JSON as parameter to Post method in controller .net api

Time:10-25

first I want to say that I'm newbie in asp.net and I'm trying to learn atleast the basic stuff for now so don't be harsh on me :) I have a post method in my controller which has to recieve a json from post request body and after that add the information to the database. So here is the method:

  [HttpPost]
    public ActionResult<DeviceData> InsertData(DeviceData deviceData)
    {
        var device = deviceContext.Devices.Find(deviceData.Id);

        if (device == null)
        {
            return BadRequest(Messages.DeviceNotExist);
        }

        deviceContext.DeviceData.Add(new DeviceData
        {
            Timestamp = DateTime.Now,
            Latitude = deviceData.Latitude,
            Longitude = deviceData.Longitude,
            Altitude = deviceData.Altitude,
            Speed = deviceData.Speed,
            DeviceId = deviceData.DeviceId
        });
        deviceContext.SaveChanges();
        return Ok(deviceContext.DeviceData.OrderBy(x=>x.Id).Last());
    }

My best guess is that my parameter is not correct since I'm trying to pass json and the paramater in the method is DeviceData type. So my question is what should I change and add to get the json body of the request and use the data to perform insert to the database and after that return a response-the json object? I'm using Postman for requests if it matters.

CodePudding user response:

When you are checking if device if exist you are using a wrong Id, you have to use DeviceId instead

 var exist = deviceContext.Devices.Any(i=> i.Id==deviceData.DeviceId);

 if (!exist) return BadRequest(Messages.DeviceNotExist);

and IMHO, replace

 deviceContext.DeviceData.Add(new DeviceData
        {
            Timestamp = DateTime.Now,
            Latitude = deviceData.Latitude,
            Longitude = deviceData.Longitude,
            Altitude = deviceData.Altitude,
            Speed = deviceData.Speed,
            DeviceId = deviceData.DeviceId
        });

with

 deviceData.Timestamp = DateTime.Now;
 deviceContext.DeviceData.Add(deviceData);
  • Related