POST method receiving object empty. W#

0

I have a controller with a POST method that always receives the null parameter. I'm sending JSON through postman.

I have tried the class as a parameter, I have already tried it by string as a parameter and in both cases it is leaving it null;

Follow the controller:

using API_Shop.AppComponents.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace API_Shop.Controllers
{
    public class TesteController : ApiController
    {
        // GET: api/Teste
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/Teste/5
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/Teste
        public void Post([FromBody]string value)
        {
            Teste tt = new Teste();
            tt = JsonConvert.DeserializeObject<Teste>(value);
            throw new Exception(tt.Texto.ToString());
        }

        // PUT: api/Teste/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/Teste/5
        public void Delete(int id)
        {
        }
    }
}

This exception is giving 'Value can not be null'. The other test informing the type of the 'Test' parameter is also getting null. In this case, the exception that is thrown is null object reference.

Follow JSON from POSTMAN:

{
  "Teste":{
  "texto":"teste de post para controller"
   }
}

Already test GET and it works normally.

Can anyone give me a hand with this? How do I get the object correctly?

    
asked by anonymous 04.02.2018 / 23:34

1 answer

0

Well, you're sending a JSON "object" as long as your Action expects a string

POST Content

{
  "Teste":{
  "texto":"teste de post para controller"
   }
}

Your Action

// POST: api/Teste
public void Post([FromBody]string value)

When you do this, you are performing POST of JSON which represents a Objeto that has another Objeto , called Teste , which in turn has atributo "text" where valor "post controller test" is declared. While in your Action you simply wait for a string.

The correct representation for this submission would be to create the objects to reflect their structure and to "typify" the input parameter of their Action

public PostApresentado
{
   public Teste Teste {get;set;}
}    

public Teste
{
   public string Texto {get; set;}
}

Your Action should expect the following input:

public void Post([FromBody]PostApresentado value)
{
}

And working this way, you do not need JsonConvert to serialize and deserialize, this is left to the framework and you can work "directly" with the objects / classes.

    
05.02.2018 / 00:29