0

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

1 Answer 1

1

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); } 
Sign up to request clarification or add additional context in comments.

2 Comments

Any links / resources ? I cant add route prefix to the whole controller. My requirement is add RPC style actions where ever needed without breaking existing route structure.
By the way can you point me to any resources where it says Attribute Routing does not work with constraints ? I could not find any from the MSDN link you provided.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.