http://attributeroute.netが最適であるというジャマーの意見に同意します。しかし、あなたがしたいことは次のことだと思います...
public class RestaurantController : ApiController
{
[GET("{countryId}/{categoryId}")]
public ActionResult ListRestaurant(string countryId, string categoryId)
{
var restaurants = from r in db.Restaurants
where r.Country.CountryId == country
where r.Category.CategoryId == categoryId
select r;
return View(restaurants);
}
}
ただし、2 つのルートを一緒に使用することはできません。最初にデータベースにアクセスせずに、「日本の最高の寿司」がカテゴリまたはレストランの名前であることをどのように解決しますか. ルーティングはコントローラーの前、つまりデータベースの前に発生するため、正しいコントローラー アクションを実行するために必要な情報がありません。
MVC ルーティングはパターン マッチングで機能するため、2 つのルートが異なるパターンを持つ必要があります。これを行う1つの方法は...
public class RestaurantController : ApiController
{
[GET("{countryId}/{categoryId:int}")]
public ActionResult ListRestaurant(string countryId, int categoryId)
{
var restaurants = from r in db.Restaurants
where r.Country.CountryId == country
where r.Category.CategoryId == categoryId
select r;
return View(restaurants);
}
[GET("{countryId}/{restaurantName:string}")]
public ActionResult ListRestaurant(string countryId, string restaurantName)
{
var restaurants = from r in db.Restaurants
where r.Country.CountryId == country
where r.Name == restaurantName
select r;
var restaurant = restaurants.SingleOrDefault();
if(restaurant == null)
return Redirect();///somewhere to tell them there is not restaurant with that name.
return View(restaurants);
}
}
最後ですが。レストラン名に国が必要な理由はありますか? 同じ名前のレストランが複数存在する可能性があるとすれば、確かに同じ国内にある可能性が高い...