MVC属性路由
本文关键字:路由 属性 MVC | 更新日期: 2023-09-27 18:18:11
是否可以在运行时修改模板中的路由?
的例子:
[Route("Home/Index")]
public View Index()
{
return View();
}
当模板没有setter时,我看到了新的IDirectRouteProvider。
我可以在别的地方做这个吗?
感谢史蒂夫别介意,
我就是这样做的,创建了我自己的路由提供程序
public class CoreEntityDirectRouteProvider : DefaultDirectRouteProvider
{
public CoreEntityDirectRouteProvider()
{
CoreEntity = Resource.CORE_ENTITY_NAME;
}
public string CoreEntity { get; private set; }
protected override IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(ActionDescriptor actionDescriptor)
{
IReadOnlyList<IDirectRouteFactory> actionRouteFactories = base.GetActionRouteFactories(actionDescriptor);
List<IDirectRouteFactory> actionDirectRouteFactories = new List<IDirectRouteFactory>();
foreach (IDirectRouteFactory routeFactory in actionRouteFactories)
{
RouteAttribute routeAttr = routeFactory as RouteAttribute;
if (routeAttr != null && !string.IsNullOrEmpty(routeAttr.Template))
{
string template = routeAttr.Template;
if (template.Contains("{{CORE_ENTITY}}"))
{
template = template.Replace("{{CORE_ENTITY}}", CoreEntity);
}
RouteAttribute routeAttribute = new RouteAttribute(template);
routeAttribute.Order = routeAttr.Order;
routeAttribute.Name = routeAttr.Name;
actionDirectRouteFactories.Add(routeAttribute);
}
}
return actionDirectRouteFactories.ToSafeReadOnlyCollection();
}
}
然后我在routecconfig中调用MapMvcAttributeRoutes时使用它,像这样:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes(new CoreEntityDirectRouteProvider());
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
如果其他人有更"合适"的方法来实现这一点,请分享。
谢谢。史蒂夫
这是我如何做到没有CoreEntityDirectRouteProvider类和删除routes.MapRoute(…)声明。
[RoutePrefix("Home")]
[Route("{action=Index}")]
public class HomeController : Controller
{
[Route("Index")]
public ActionResult Index()
{
return View();
}