Home > Mobile >  Why does my response from endpoint in .NET 6 API always change to an empty array?
Why does my response from endpoint in .NET 6 API always change to an empty array?

Time:09-23

I am creating a post type endpoint to create a record, but the answer, whether correct or incorrect, changes the result to an empty array.

this is the endpoint

[HttpPost("CrearRol")]
        public async Task<IActionResult> CrearRol(Role rol)
        {
            var x = await _roles.CrearRol(rol);
            return x;
        }

And this is de method CrearRol

public async Task<IActionResult> CrearRol(Role rol)
        {
            try
            {
                var roleBuscado = _context.Roles.Where(e => e.NombreRol == rol.NombreRol.Trim() && e.Estado== "A").FirstOrDefault();
                if (roleBuscado != null)
                {
                    return _error.respuestaDeError("El rol '" rol.NombreRol "' ya existe");
                }
                Role rolNuevo = new Role();
                rolNuevo.NombreRol = rol.NombreRol;
                rolNuevo.UsuarioIng = rol.UsuarioIng;
                rolNuevo.FechaIng = DateTime.Now;
                rolNuevo.Estado = "A";
                _context.Roles.Add(rolNuevo);
                await _context.SaveChangesAsync();
                JObject respuesta = new JObject
                {
                    ["message"] = 1
                };
                return new ObjectResult(respuesta) { StatusCode = 200 };

            }catch (Exception ex)
            {
                return _error.respuestaDeError("Error al momento de crear el rol", ex);
            }
        }

Succes responce

{
  "message": []
}

Error responce

{
    "error": []
}

when you debug the response this is displayed correctly like this Correct Succes responce

{
    "message": "succes save"
}

Correct Error responce

{
    "error": "string with error information"
}

I try from postman, insomnia, swagger, angular and the responce is always bad

CodePudding user response:

try this

return Ok( new { message=1 });

CodePudding user response:

The correct answer is in the comments of the first post. But I'll also put it here

Add this nuget package in your proyect

Microsoft.AspNetCore.Mvc.NewtonsoftJson

In my case version 6 but it may vary depending on your .net version

And add '.AddNewtonsoftJson();' in your program.cs, in this way:

builder.Services.AddControllers().AddNewtonsoftJson();
  • Related