There are many questions in this topic, but I hardly find to address my problem.
Likewise Stackoverflow, I would like to get question(master) and replies(details) hierarchical json with below four cases.
- /api/question/ : list of questions
- /api/question/{id} : question of the ID
- /api/question/{id}/reply/ : list of replies with the question.
- /api/question/{id}/reply/{rid} : one reply item of the question.
Top two urls are not a problem as WebApi CRUD generates for me.
But below two urls, I cannot make it.
The methods below are related ones in QuestionController
(Note that controller name is Question).
// case 1.
public virtual Question Get(){
// return list of questions
}
// case 2.
public virtual Question Get(Int64 id)
{
// return question item.
var item = ((IQuestionRepository)repository).GetFirstFiltered(n => n.Id == id);
return item;
}
// case 3.
public virtual Question GetReply(Int64 id)
{
// return a list of replies
}
// case 4.
public virtual Question GetReply(Int64 id, Int64 rid)
{
// return reply item of rid.
}
First try
I added route above default route as below, but only fourth method is triggered. third is omitted.
config.Routes.MapHttpRoute(
name: "QuestionApi",
routeTemplate: "api/{controller}/{id}/reply/{rid}",
defaults: new
{
controller = "Question",
rid = RouteParameter.Optional
}
);
Second try
I created newly introduced Route attribute in WebApi2. does not hit in case 3 and 4.
// case 3.
[Route("reply")]
public virtual Question GetReply(Int64 id)
{
// return list of reply
}
// case 4.
[Route("reply/{rid}")]
public virtual Question Get(Int64 id, Int64 rid)
{
// return reply item
}
Route works if I set from very first address as "~api/{controller}/{id}/reply"
, but it doesn't seem to be good solution.
How can I make it?