Reputation: 991
Why does the third route fail in my Web API ?
public class StudentCourseController : ApiController
{
// GET api/student
public IEnumerable<StudentCourse> Get()
{
return StudentCourseRepository.GetAll();
}
// GET api/student/5
public StudentCourse Get(int id)
{
return StudentCourseRepository.GetAll().FirstOrDefault(s => s.Id == id);
}
[Route("StudentAuto/{key}")] // Does not work
public IEnumerable<Student> StudentAuto(string key)
{
return StudentRepository.GetStudentsAuto(key);
}
When i request http://localhost:5198/api/StudentCourse/StudentAuto/mi
I get a 404 error.
The detail error shows
Requested URL http://localhost:5198/api/StudentCourse/StudentAuto/mi
Physical Path C:\Users\deb\Desktop\StudentKO\KnockoutMVC\KnockoutMVC\api\StudentCourse\StudentAuto\mi
Logon Method Anonymous
Logon User Anonymous
Did i miss anything ?
thanks
Upvotes: 0
Views: 224
Reputation: 16609
Attribute routing on a method does not work in conjunction with the route constraints for the controller you put into your startup, e.g. "/api/{controller}"
.
Therefore your [Route("StudentAuto/{key}")]
route literally maps to "/StudentAuto/{key}"
, not "/api/StudentCourse/StudentAuto/{key}"
.
You can get this to work as you want by adding a [RoutePrefix]
(see msdn) to your controller:
[RoutePrefix("api/StudentCourse")]
public class StudentCourseController : ApiController
{
}
Alternatively just set the whole path in your Route
attribute:
[Route("api/StudentCourse/StudentAuto/{key}")]
public IEnumerable<Student> StudentAuto(string key)
{
return StudentRepository.GetStudentsAuto(key);
}
Upvotes: 1