我需要创建一个自定义操作过滤器属性,其中包含2个“RouteAttibute”过滤器的声明。
我需要:
[Contains2Routes]
public ActionResult Index()
{
return View();
}
而不是:
[Route("~/index1")]
[Route("~/index2")]
public ActionResult Index()
{
return View();
}
感谢帮助者!
答案 0 :(得分:0)
可能这不是最好的方法,但你可以通过这样的自定义路由属性来实现:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
public sealed class MultiRouteAttribute : Attribute, IDirectRouteFactory
{
public string Name { get; set; }
public int Order { get; set; }
public string[] Templates { get; private set; }
public MultiRouteAttribute(string[] template)
{
this.Templates = template;
}
RouteEntry IDirectRouteFactory.CreateRoute(DirectRouteFactoryContext context)
{
var template = "~/{Type:regex(" + string.Join("|", Templates) + ")}";
IDirectRouteBuilder builder = context.CreateBuilder(template);
builder.Name = this.Name;
builder.Order = this.Order;
return builder.Build();
}
}
你可以这样使用它:
[MultiRoute(new[] { "index1", "index2" })]
public ActionResult Index()
{
return View();
}
而不是:
[Route("~/index1")]
[Route("~/index2")]
public ActionResult Index()
{
return View();
}
此解决方案比内置RouteAttribute
更受限制,因为它只是在路由中使用regexp