I’ve created a controller class:
[Route("api/[controller]")]
[ApiController]
public class CourseController : ControllerBase
I’ve got methods for the route declared in the attribute above but I also want to handle a subroute, eg. "api/[controller]/{id}/course_subjects"
. I’ve tried adding the Route attribute to the method but after running the application I see a Swagger error and no response from that route when I type it in the browser.
The method:
[HttpGet("{id}")]
public async Task<IEnumerable<SubjectDto>> GetCourseSubjectsList(string courseId)
{
return await _courseProcessor.GetSubjectsForCourseAsync(courseId);
}
This is how I add the Route
[HttpGet("{id}")]
[Route("api/[controller]/{id}/course_subjects/")]
public async Task<IEnumerable<SubjectDto>> GetCourseSubjectsList(string courseId)
{
return await _courseProcessor.GetSubjectsForCourseAsync(courseId);
}
If I add the route directly in the HttpGet attribute, I get an error about the parameter being missing.
[HttpGet("{id}/course_subjects")]
public async Task<IEnumerable<SubjectDto>> GetCourseSubjectsList(string courseId)
{
return await _courseProcessor.GetSubjectsForCourseAsync(courseId);
}
The error in the browser:
type "https://tools.ietf.org/html/rfc7231#section-6.5.1"
title "One or more validation errors occurred."
status 400
traceId "00-9c0f1c8198ed9573148cd3628c358ee3-87d7adc13bc3db77-00"
errors
courseId
0 "The courseId field is required."
What am I doing wrong?
2
Answers
I figured it out. When I used the subroute in the HttpGet attribute, I didn't use a matching parameter name for the attribute and the method argument. In the attribute I used
id
and in the method argument I usedcourseId
.So the code should be:
you do not need
Route
attribute at all. You can specify the route in theHttpGet
[HttpGet("{id}/course_subjects")]