I can not give POST with WebAPI

0

I'm studying WebAPI and using Postman to test. By doing some tests I realized that nothing comes when I send json using Postman for WebAPI. I searched a lot about POST using WebAP, but I do not know why it's not working ...

Follow the Controller code:

using Microsoft.AspNet.Mvc;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApi.Model;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    public class ClienteController : ApiController
    {
        private IList<Cliente> novosClientes = new List<Cliente>();

        private Cliente[] Clientes = new Cliente[]
        {
            new Cliente { ID = 1, Nome = "Joel Jordison", Email = "[email protected]", Ativo = true },
            new Cliente { ID = 2, Nome = "Bill Gates", Email = "[email protected]", Ativo = true },
            new Cliente { ID = 3, Nome = "Aleister Crowley", Email = "[email protected]", Ativo = false }
        };

        // GET: api/cliente
        [HttpGet]
        public Cliente[] Get()
        {
            return Clientes;
        }

        // POST api/cliente
        [HttpPost]
        public HttpResponseMessage Post(Cliente value)
        {
            Debug.WriteLine("Começo");

            Debug.WriteLine("-------------Value-----------------");
            Debug.WriteLine(value.ID);
            Debug.WriteLine(value.Nome);
            Debug.WriteLine(value.Email);
            Debug.WriteLine(value.Ativo);
            Debug.WriteLine("-------------Fim Value-------------");

            if (value != null)
            {
                Debug.WriteLine("Não nulo");
                novosClientes.Add(value);
                Clientes = novosClientes.ToArray();
                return new HttpResponseMessage(HttpStatusCode.OK);
            }

            Debug.WriteLine("Fim");

            return new HttpResponseMessage(HttpStatusCode.BadRequest);
        }
    }
}

I'm trying to send json by selecting POST, then I Body and putting json in Postman like this:

{
    "ID": 10, 
    "Nome": "Joana", 
    "Email": "[email protected]", 
    "Ativo": true 
}

In response, I get this:

{
  "Version": {
    "Major": 1,
    "Minor": 1,
    "Build": -1,
    "Revision": -1,
    "MajorRevision": -1,
    "MinorRevision": -1
  },
  "Content": null,
  "StatusCode": 200,
  "ReasonPhrase": "OK",
  "Headers": [],
  "RequestMessage": null,
  "IsSuccessStatusCode": true
}
    
asked by anonymous 13.07.2016 / 01:21

2 answers

2

The attribute Route should not be there. This attribute is used to define a route to a method , so it should not be applied to the class. Also, its value is wrong, if you want your route to be api / controller you will not need the attribute, taking into account that you have the default Web API routes configured in the WebApiConfig.cs . If you do not have the default routes configured for some reason, you should change the attribute and its value to

[RoutePrefix("api/clientes")]
public class ClienteController : ApiController { ... }

Note: When defining a method called Get it will be automatically mapped to HTTP GET verb, so the attribute [HttpGet] is unnecessary, but that does not make a difference, you can keep it right there.

If you need to, here is the default route setting

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
    
13.07.2016 / 04:04
0

I do not usually use postMan for tests, I like to create an html with js, follow an example that I created for my tests below, to work with your example just change the URL and parameters of your object. / p>

HTML example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title></title>  
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script><script>$(function(){$.post("http://localhost:51589/api/Usuarios",{Nome:'Adriano',PerfilId:1}, function( data ) {
                alert('Usuário salvo com sucesso!');
            });
        }); 
    </script>
</head>
<body> 
</body>
</html>

Example Api

 // POST api/USuarios
        [ResponseType(typeof(Usuario))]
        public IHttpActionResult PostUsuario(Usuario usuario)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }    


     return CreatedAtRoute("DefaultApi", new { id = usuario.Id }, usuario);
        }
    
13.07.2016 / 16:39