ASP.NET Web Api を使用して実装したい次のレスト スキーマがあります。
http://mydomain/api/students
http://mydomain/api/students/s123
http://mydomain/api/students/s123/classes
http://mydomain/api/students/s123/classes/c456
ApiController と次の 2 つの方法を使用して、最初の 2 つのリンクが正しく機能しています。
public class StudentsController : ApiController {
// GET api/students
public IEnumerable<Student> GetStudents() {
}
// GET api/students/5
public IEnumerable<Student> GetStudent(string id) {
}
}
この同じコントローラー (または、ClassesController という別のコントローラーが必要ですか?) で、最後の 2 つのリンクをどのように実装しますか? また、「クラス」部分のルーティングはどのようになりますか (必要な場合)?
これが私の WebApiConfig です (可能であれば /classes へのルートをハードコーディングするのではなく、動的に保ちたいと思います:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// EDIT - I'm getting 404's when trying to use this
context.Routes.MapHttpRoute(
name: "JobsApi",
routeTemplate: this.AreaName + "/Students/{id}/Classes/{classId}",
defaults: new { classId = RouteParameter.Optional }
);
編集これが私の新しく作成されたClassesControllerです:
public class ClassesController : ApiController {
// GET api/classes
public IEnumerable<TheClass> Get(string id) {
return null;
}
}
この URL にアクセスしようとすると、404 エラーが発生します。
http://mydomain/api/students/s123/classes