可能是不做到這一點的最好辦法,但你可以做到這一點與自定義路由屬性那樣:
[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
,因爲它只是在路由中使用正則表達式
首先感謝,第二,如果我想添加參數,默認值和約束,該怎麼辦? –