How should I resolve ASP.NET Core multiple endpoints error

Advertisements

My controller is:

[Route("api/[controller]")]
[ApiController]
public class SubjectController : ControllerBase
{
    private TourActivityExpenseContext tourActivityExpenseContext = new TourActivityExpenseContext();
      
    [HttpGet]
    public IEnumerable<SubjectTo> Get()
    {
        var subjects = tourActivityExpenseContext.SubjectTos.ToList();
        return subjects;
    }

    [HttpGet("{subject}")]
    public int GetSubjectId(String subject)
    {
        var subjects = tourActivityExpenseContext.SubjectTos.ToList();
        var isSub = subjects.FirstOrDefault(x => x.Subject == subject);
        int id = isSub.Id;
        return id;
    }
    
    [HttpGet("{id}")]
    public string Get(int id)
    {
        var subjects = tourActivityExpenseContext.SubjectTos.ToList();
        var isSub = subjects.FirstOrDefault(x => x.Id == id);
        String sub = isSub.Subject;
        return sub;
    }
}

When requested in Postman with an URL like

http://localhost:5000/api/Subject/Meeting

I get an error like this:

Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints. Matches:

TourExp.Controllers.SubjectController.Get (TourExp)
TourExp.Controllers.SubjectController.GetSubjectId (TourExp)

>Solution :

Try to give them a specific route :

        [HttpGet("GetSubject/{subject}")]
        public int GetSubjectId(String subject)
        {

            var subjects = tourActivityExpenseContext.SubjectTos.ToList();
            var isSub = subjects.FirstOrDefault(x => x.Subject == subject);
            int id = isSub.Id;
            return id;
        }

Leave a ReplyCancel reply