Вы можете написать собственный маршрут:
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 }
);
}
и, наконец, у вас может быть свой контроллер категорий:
public class CategoriesController : Controller
{
public ActionResult Index(string id)
{
...
}
}
Сейчас:
http://localhost:7060/bizcontacts
выполнит действие Index
контроллера Categories
и передаст id = 1
http://localhost:7060/homecontacts
выполнит действие Index
контроллера Categories
и передаст id = 3
http://localhost:7060/othercontacts
выполнит действие Index
контроллера Categories
и передаст id = 4