skip to Main Content

I’m trying to pass in a string,sigla do Curso, and use the get method to return the object equivalent to this acronym, but the output returns an error

Error:

{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-8db2fbce7dfcc684ce94f0e8b4baaab1-67a764080f12fca7-00",
"errors": {
    "id": [
        "The value 'enc' is not valid."
    ]
}

}

Code:

// GET: api/Cursos/LES
        [HttpGet("cursos/{sigla}")]
        public async Task<ActionResult<Curso>> GetCurso(string sigla)
        {
            if (_context.Cursos == null)
            {
                return NotFound();
            }
            var curso = await _context.Cursos.Include(f => f.Sigla).
            FirstOrDefaultAsync(a => a.Sigla == sigla);

            
            if (curso == null)
            {
                return NotFound();
            }

            return curso;
        }

Class curso:

namespace UniversidadeApi.Models
{
    public class Curso
    {
        public long Id { get; set; }
        public string? Sigla { get; set; }
        public string? Nome { get; set; }
 
    }
}

URL used to send a get request:
https://localhost:7225/api/cursos/enc

I also tested with the urls:
https://localhost:7225/api/cursos/ENC
https://localhost:7225/api/cursos/"ENC"

The object I created with the post method:

 {
    "id": 1,
    "sigla": "ENC",
    "nome": "Engenharia da Computação"
}

2

Answers


  1. Chosen as BEST ANSWER

    I just change the var curso line to this new line and it worked

    var curso = await _context.Cursos.FirstOrDefaultAsync(a => a.Sigla == sigla);
    

  2. Try to use [FromRoute] attribute with your parameter. Like this:

    [HttpGet("cursos/{sigla}")]
    public async Task<ActionResult<Curso>> GetCurso([FromRoute] string sigla)
    {
    ...
    }
    

    More about model binding here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search