I can’t post with Webapi

Asked

Viewed 934 times

0

I’m studying Webapi and using Postman to test it. Doing some tests I realized that nothing comes when I send json using Postman to Webapi. I researched a lot about POST using Webap, but I don’t 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 the json by selecting POST, then I Body and putting the json in Postman like this:

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

As an answer, 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
}

3 answers

2

The attribute Route should not be there. This attribute is used to set a route to a method, so it shouldn’t be applied in the class. Also, its value is wrong if you want your route to be api/controller will not need the attribute, this taking into account that you have the default Web API routes configured in the file WebApiConfig.cs. If you don’t have default routes set up 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 verb GET, soon the attribute [HttpGet] it’s unnecessary, but it makes no difference, it can keep you right there.


If you need to, here’s the default route configuration

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 }
        );
    }
}
  • I still can’t do a POST. When I try to do the POST I get this XMLHttpRequest cannot load http://localhost:50143/api/Cliente. Response for preflight has invalid HTTP status code 405

0

I don’t usually use Postman for tests, I like to create html with js, follow an example I created for my tests below, to work with your example just change the URL and the parameters of your object.

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);
        }
  • Which version do you use on Webapi? Thanks for your help!

  • 1

    I’m using the 2.0

  • In my example, you saw something wrong?

  • I tried your example and I got Request Method:POST Status Code:200 OK, but when I give a GET I see that you have not updated the array

  • you saw in firebug if the return of your get is not with No 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin ?

  • Yes, I tried. Nothing came of it.

Show 1 more comment

0

I have been through this type of problem and to solve I made two changes, but one of them is not the case.

The POST method declaration snippet as it is when you make a request the system cannot perform the automatic conversion of Json to the Client object. You must make explicit which Binding structure the parameter will use. In this case, as the request has the Json informed in the body then you must declare the method as follows:

`

    [HttpPost]
    public HttpResponseMessage Post([FromBody] 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);
    }

`

Browser other questions tagged

You are not signed in. Login or sign up in order to post.