【发布时间】:2014-03-05 10:08:13
【问题描述】:
当我们对每个方法都有多个所需的路由级别时,有没有办法简化?
我有一个假设的 WebAPI 项目,我正在使用它来对问题进行一般性的研究。它为我们提供了一些来源的电影。
public class MovieController : ApiController
{
// GET api/<controller>
public IEnumerable<Movie> Get()
{
return MoviesDB.All();
}
// GET api/<controller>/5
public Movie Get(int id)
{
return MoviesDB.ThisSpecificOne(id);
}
// POST api/<controller>
public void Post([FromBody]Movie value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]Movie value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
但是让我们说一些愚蠢的原因电影是按流派存储的。所以你需要流派 + id 组合。
我假设你会这样做
config.Routes.MapHttpRoute(
name: "MoviesWithGenre",
routeTemplate: "api/{controller}/{genre}/{id}",
defaults: new { id = RouteParameter.Optional }
);
public class MovieController : ApiController
{
// GET api/<controller>/<genre>
public IEnumerable<Movie> Get(string genre)
{
return MoviesDB.All(genre);
}
// GET api/<controller>/<genre>/5
public Movie Get((string genre, int id)
{
return MoviesDB.ThisSpecificOne(string genre, id);
}
// POST api/<controller>/<genre>
public void Post(string genre, [FromBody]Movie value)
{
}
// PUT api/<controller>/<genre>/5
public void Put(string genre, int id, [FromBody]Movie value)
{
}
// DELETE api/<controller>/<genre>/5
public void Delete(string genre, int id)
{
}
}
所以现在MySite.Com/api/movie/horror/12345 可能会返回一部电影,但我需要在每个方法中添加可选参数。现在我发现它们也是按年份存储的。
config.Routes.MapHttpRoute(
name: "MoviesWithGenreAndYear",
routeTemplate: "api/{controller}/{genre}/{year}/{id}",
defaults: new { id = RouteParameter.Optional }
);
public class MovieController : ApiController
{
// GET api/<controller>/<genre>/<year>
public IEnumerable<Movie> Get(string genre, int year)
{
return MoviesDB.All(string genre, int year);
}
// GET api/<controller>/<genre>/<year>/5
public Movie Get(string genre, int year, int id)
{
return MoviesDB.ThisSpecificOne(string genre, int year, id);
}
// POST api/<controller>/<genre>/<year>
public void Post(string genre, int year, [FromBody]Movie value)
{
}
// PUT api/<controller>/<genre>/<year>/5
public void Put(string genre, int year, int id, [FromBody]Movie value)
{
}
// DELETE api/<controller>/<genre>/<year>/5
public void Delete(string genre, int year, int id)
{
}
}
这一切都很好,但是对于每个新层,您都需要为每个方法添加一个新参数。感觉不是很DRY
我能否将这些层注入构造函数而不是方法本身。
也许我想根据这些层以不同的方式初始化控制器,所以我会根据流派和/或年份或类似的东西有一个不同的 repo。
有解决办法吗?
【问题讨论】:
标签: c# asp.net-web-api dry asp.net-web-api-routing asp.net-web-api2