你可以寫一個自定義路由:
public class MyRoute : Route
{
private readonly Dictionary<string, string> _slugs;
public MyRoute(IDictionary<string, string> slugs)
: base(
"{slug}",
new RouteValueDictionary(new
{
controller = "categories", action = "index"
}),
new RouteValueDictionary(GetDefaults(slugs)),
new MvcRouteHandler()
)
{
_slugs = new Dictionary<string, string>(
slugs,
StringComparer.OrdinalIgnoreCase
);
}
private static object GetDefaults(IDictionary<string, string> slugs)
{
return new { slug = string.Join("|", slugs.Keys) };
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var rd = base.GetRouteData(httpContext);
if (rd == null)
{
return null;
}
var slug = rd.Values["slug"] as string;
if (!string.IsNullOrEmpty(slug))
{
string id;
if (_slugs.TryGetValue(slug, out id))
{
rd.Values["id"] = id;
}
}
return rd;
}
}
可能在Application_Start
在global.asax
註冊:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(
"MyRoute",
new MyRoute(
new Dictionary<string, string>
{
{ "BizContacts", "1" },
{ "HomeContacts", "3" },
{ "OtherContacts", "4" },
}
)
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
最後你可以有你的CategoriesController:
public class CategoriesController : Controller
{
public ActionResult Index(string id)
{
...
}
}
現在:
http://localhost:7060/bizcontacts
將擊中Categories
控制器的Index
動作並傳遞ID = 1
http://localhost:7060/homecontacts
將擊中Categories
控制器的Index
動作並傳遞ID = 3
http://localhost:7060/othercontacts
將擊中Categories
控制器的Index
動作和傳ID = 4
如果類別名稱將是獨一無二的,爲什麼不把它們作爲你的過濾器? – 2012-02-14 23:13:00