2015-12-06 63 views
0

爲什麼我的Web API中的第三條路由失敗?Web API中的屬性路由失敗2

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); 
     } 

當我要求http://localhost:5198/api/StudentCourse/StudentAuto/mi我收到404錯誤。

詳細錯誤顯示

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 

我錯過了什麼?

感謝

回答

1

屬性的路由上的方法結合路線約束,你把你的啓動,例如控制器不工作"/api/{controller}"

因此,您的[Route("StudentAuto/{key}")]路線字面上映射到"/StudentAuto/{key}",而不是"/api/StudentCourse/StudentAuto/{key}"

你可以得到這個加入,只要你想工作[RoutePrefix](見msdn)到你的控制器:

[RoutePrefix("api/StudentCourse")] 
public class StudentCourseController : ApiController 
{ 
} 

或者剛剛設置的整個路徑在Route屬性:

[Route("api/StudentCourse/StudentAuto/{key}")] 
public IEnumerable<Student> StudentAuto(string key) 
{ 
    return StudentRepository.GetStudentsAuto(key); 
} 
+0

任何鏈接/資源?我不能添加路由前綴到整個控制器。我的要求是在不破壞現有路線結構的情況下添加RPC風格的動作。 – Deb

+0

完整路徑的工作。謝謝你的幫助。 – Deb

+0

順便說一句,您可以指向我說的任何資源,它說屬性路由不適用於約束?我找不到您提供的MSDN鏈接。 – Deb