在ASP.NET Web api项目中,我有一个VacationController,我希望使用这些操作方法。 我如何构建路线来实现这一目标?具有不同参数的多个操作的Web api路由
public Enumerable<Vacation> GetVacation()
{
// Get all vactions
return vacations;
}
public Vacation GetVacation(int id)
{
// Get one vaction
return vacation;
}
public Enumerable<Vacation> ByThemeID(int themeID)
{
// Get all vactions by ThemeID
return vacations;
}
我想网址看起来像这样
/api/vacation // All vacations
/api/vacation/5 // One vacation
/api/vacation/ByThemeID/5 // All vacations from one theme
编辑30-10-2013
我已经试过Pasit [R路线,但我不能让工作。我真的尝试了所有我能想到的组合。
这就是我所知道的。正如你所看到的,我在路线的另一边添加了一个额外的参数。我意识到我需要这样做才能将不同标签上出售的假期分开。
这里是我使用的路线。和最后URL
config.Routes.MapHttpRoute(
name: "DefaultApiSimbo",
routeTemplate: "api/{label}/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
在这里,在VacationController
// ByThemeID api/{label}/Vacation/ByThemeId/{id}
[HttpGet]
public IEnumerable<Vacation> ByThemeID(string label, int id)
{
return this.repository.Get(label);
}
// GET api/{label}/Vacation
public IEnumerable<Vacation> GetVacation(string label)
{
return repository.Get(label);
}
// GET api/{label}/Vacation/{id}
public Vacation GetVacation(string label, int id)
{
Vacation vacation;
if (!repository.TryGet(label, id, out vacation))
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
return vacation;
}
我的行动方法能有人给这些URL的
/api/vacation // All vacations
/api/vacation/5 // One vacation
/api/vacation/ByThemeID/5 // All vacations from one theme
但工作不到风度的工作OK我推着正确的方向;-)
在此先感谢
安德斯·彼得森
你想要什么样子的路线?大约有无数种不同的方式可以设置路线来访问这些方法。 –