[英]ASP.NET MVC 4 routing friendly URL
我发现这个网站有不错的网址。 但是我不知道如何创建这样的路线。 我的格式是这样的:
www.domain.com/{country}/{category-name} ---> www.domain.com/japanese/restaurant
www.domain.com/{country}/{restaurant-name} ---> www.domain.com/japanese/the-best-sushi-of -japanese
有什么建议么?
您应该使用http://attributerouting.net/
它使您可以在课堂上执行以下操作:
[RoutePrefix("my")]
public class MyController : ApiController
然后在您的方法上:
[POST("create"), JsonExceptionFilter]
public HttpResponseMessage CreateEntry(Entry entryDc)
因此,您的网址是:
http://www.mydomain/my/create
同意Jammer的建议,即使用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);
}
}
但是,您无法同时使用两条路线。 如何确定“日本最好的寿司”是餐厅的类别或名称,而无需先进入数据库。 由于路由发生在控制器之前,因此在数据库之前发生,因此您没有执行正确的Controller Action所需的信息。
MVC路由适用于模式匹配,因此您需要两条路由具有不同的模式。 您可以执行此操作的一种方法是...
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);
}
}
最后虽然。 您为什么需要餐厅名称的国家? 如果您假设存在多个同名餐厅的可能性,那么肯定在同一个国家/地区更可能...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.