1

I created an ASP.NET Core Web API project with the default Visual Studio template, disabling the configure for https checkmark and whenever I am trying to run my application, I get this error shown here:

An unhandled exception occurred while processing the request. InvalidOperationException: Body was inferred but the method does not allow inferred body parameters.

Below is the list of parameters that we found:

Parameter Source
empleadoService Body (Inferred)
idEmpleado Route (Inferred)

Did you mean to register the "Body (Inferred)" parameter(s) as a Service or apply the [FromServices] or [FromBody] attribute?

This error is shown when I try to implement

app.MapDelete("/employee/delete/{idEmployee}

I have read several articles and I have not been able to find a solution to my problem.

This is my Program.cs code

using BackEndApiProject.Models;
using Microsoft.EntityFrameworkCore;

using BackEndApiProject.Services.Contrato;
using BackEndApiProject.Services.Implementacion;
using AutoMapper;
using BackEndApiProject.Utilidad;
using BackEndApiProject.DTO;
using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// configuracion del contexto
builder.Services.AddDbContext<DbempleadoContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("cadenaSQL"));
});

builder.Services.AddScoped<IDepartamentoService, DepartamentoService>();
builder.Services.AddScoped<IEmpleadoService, EmpleadoService>();
builder.Services.AddAutoMapper(typeof(AutoMapperProfile));
builder.Services.AddCors(options =>{
    options.AddPolicy("nuevaPolitica", app =>
    {
        app.AllowAnyOrigin()
        .AllowAnyHeader()
        .AllowAnyMethod();
    });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

#region Peticiones API Rest Empleados

// listado de empleados
app.MapGet("/empleado/lista", async (IEmpleadoService empleadoService,
    IMapper mapper) =>
{
    var listaEmpleado = await empleadoService.GetList();
    var listaEmpleadoDTO = mapper.Map<List<EmpleadoDTO>>(listaEmpleado);

    if (listaEmpleadoDTO.Count > 0)
        return Results.Ok(listaEmpleadoDTO);
    else
        return Results.NotFound();
});

// Buscar Empleado por id
app.MapGet("/empleado/{idEmpleado}", async (int idEmpleado,
    IEmpleadoService empleadoService,
    IMapper mapper) =>
{
    var encontrado = await empleadoService.Get(idEmpleado);

    if (encontrado == null)
    {
        return Results.NotFound();
    }
    else
    {
        var empleadoDTO = mapper.Map<EmpleadoDTO>(encontrado);
        return Results.Ok(empleadoDTO);
    }
});

// Guardar un empledado
app.MapPost("/empleado/guardar", async (EmpleadoDTO modelo,
    IEmpleadoService empleadoService,
    IMapper mapper) =>
{
    var empleado = mapper.Map<Empleado>(modelo);
    var empleadoCreado = await empleadoService.Add(empleado);

    if (empleadoCreado.IdEmpleado != 0)
    {
        return Results.Ok(mapper.Map<EmpleadoDTO>(empleadoCreado));
    }
    else
    {
        return Results.StatusCode(StatusCodes.Status500InternalServerError);
    }
});

// Actualizar un empleado
app.MapPut("/empleado/actualizar/{idEmpleado}", async (int idEmpleado,
    EmpleadoDTO modelo,
    IEmpleadoService empleadoService,
    IMapper mapper) =>
{
    var encontrado = await empleadoService.Get(idEmpleado);

    if (encontrado is null)
    {
        return Results.NotFound();
    }
    else
    {
        var empleado = mapper.Map<Empleado>(modelo);
        encontrado.NombreCompleto = empleado.NombreCompleto;
        encontrado.Sueldo = empleado.Sueldo;
        encontrado.IdDepartamento = empleado.IdDepartamento;
        encontrado.FechaContrato = empleado.FechaContrato;
        var resppuesta = await empleadoService.Update(encontrado);

        if (resppuesta)
        {
            return Results.Ok(mapper.Map<EmpleadoDTO>(encontrado));
        }
        else 
        { 
            return Results.StatusCode(StatusCodes.Status500InternalServerError); 
        }
    }
});

// Eliminar un empleado
app.MapDelete("/empleado/eliminar/{idEmpleado}", async (EmpleadoService empleadoService,
    int idEmpleado) =>
{
    var encontrado = await empleadoService.Get(idEmpleado);

    if (encontrado is null)
    {
        return Results.NotFound();
    }
    else
    {
        var respuesta = await empleadoService.Delete(encontrado);

        if (respuesta)
            return Results.Ok();
        else
            return Results.StatusCode(StatusCodes.Status500InternalServerError);
    }
});

#endregion

app.UseCors("nuevaPolitica");

app.Run();

This is my Empleado class:

public class EmpleadoDTO
{
    public int IdEmpleado { get; set; }

    public string? NombreCompleto { get; set; }
    public int? IdDepartamento { get; set; }
    public string? NombreDepartamento { get; set; }
    public int? Sueldo { get; set; }
    public string? FechaContrato { get; set; }
}

This is my EmpleadoService class:

public class EmpleadoService : IEmpleadoService
{
    private DbempleadoContext _dbempleadoContext;

    public EmpleadoService(DbempleadoContext dbempleadoContext)
    {
        this._dbempleadoContext = dbempleadoContext;
    }

    public async Task<List<Empleado>> GetList()
    {
        try
        {
            var lista = new List<Empleado>();
            lista = await this._dbempleadoContext.Empleados.Include(dpt => dpt.IdDepartamentoNavigation).ToListAsync();
            return lista;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public async Task<Empleado> Get(int id)
    {
        try
        {
            Empleado? empleado = new Empleado();
            empleado = await _dbempleadoContext.Empleados.Include(dpt => dpt.IdDepartamentoNavigation)
                .Where(idEmp => idEmp.IdEmpleado == id).FirstOrDefaultAsync();
            return empleado;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public async Task<Empleado> Add(Empleado modelo)
    {
        try
        {
            _dbempleadoContext.Empleados.Add(modelo);
            await _dbempleadoContext.SaveChangesAsync();
            return modelo;
        }
        catch (Exception ex)
        {
            throw ex; 
        }
    }

    public async Task<bool> Update(Empleado modelo)
    {
        try
        {
            _dbempleadoContext.Empleados.Update(modelo);
            await _dbempleadoContext.SaveChangesAsync();
            return true;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public async Task<bool> Delete(Empleado modelo)
    {
        try
        {
            _dbempleadoContext.Empleados.Remove(modelo);
            await _dbempleadoContext.SaveChangesAsync();
            return true;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

I want to be able to delete an employee given his Id.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

From the following:

app.MapDelete("/empleado/eliminar/{idEmpleado}", async (
   EmpleadoService empleadoService, 
   int idEmpleado) =>

And other methods - it seems you have registered IEmpleadoService, not EmpleadoService (so the framework infers that this parameter is from body, not from services), so fix that and it should work:

app.MapDelete("/empleado/eliminar/{idEmpleado}", async (
   int idEmpleado, 
   IEmpleadoService empleadoService) =>

Alternatively you can be explicit about binding sources:

app.MapDelete("/empleado/eliminar/{idEmpleado}", async (
   [FromRoute] int idEmpleado, 
   [FromServices] IEmpleadoService empleadoService) =>
Guru Stron
  • 102,774
  • 10
  • 95
  • 132